C++ 方法名和枚举类名冲突

标签 c++

我有一个类,其中有一个“type”方法和一个枚举类“type”。我想让两者都命名为“类型”。

class proxy {
public:
    enum class type { direct, http };
    enum type type() const { return type_; }
private:
    enum type type_ = type::direct;
};

编译时出现如下错误:

 error: ‘type’ is not a class, namespace, or enumeration
 enum type type_ = type::direct;

我知道那是因为我的类型方法隐藏了枚举类类型。有可能用 C++ 解决这个问题吗?

最佳答案

对于 VS 2015,这为我编译:

class proxy {
public:
    enum class type { direct, http };
    enum class type type() const { return type_; }
private:
    enum class type type_ = type::direct;
};

您只需添加“class”关键字,因为它是一个作用域枚举。

VS 的用法:

proxy p;
enum class proxy::type var = p.type();

您的原始解决方案针对 gcc 6.3 和 clang 3.9.1 进行编译:

class proxy {
public:
    enum class type { direct, http };
    enum type type() const { return type_; }
private:
    enum type type_ = type::direct;
};

clang 和 gcc 的用法:

proxy p;
enum proxy::type var = p.type();

对于 gcc 5.4,您可以在类的私有(private)部分中对枚举进行类型定义。

关于C++ 方法名和枚举类名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606093/

相关文章:

c++ - WTL CIdleHandler 的正确用法是什么?

c++ - SDL_WM_SetCaption 不工作

C++ <type>*& 类函数或结构错误

c++ - Qt 如何从 QVector 的数据创建位图并将其显示在小部件上?

c++ - 如何使用dll?

php - linux下C和PHP进程间通信有什么好的方法

c++ - 如何计算具有特定 roi 大小的图像的 std dev?

c++ - 如何在 XCode 7 中应用支持 OpenMP

c++ - 将 lambda 作为参数传递时参数推导失败

用于生成部分 switch 语句的 C++ 模板?