C++ 枚举重新定义和 C++0x

标签 c++ enums c++11

如果我想在 C++ 中排除枚举和类型重定义的问题,我可以使用代码:

struct VertexType
{
    enum
    {
        Vector2 = 1,
        Vertor3 = 2,
        Vector4 = 3,
    };
};

struct Vector2 { ... };
struct Vector3 { ... };
struct Vector3 { ... };

有没有办法删除枚举上面的包装器。我查看了 C++0x,但没有找到有关解决此问题的其他信息。

最佳答案

因为你在谈论 C++0x,只需使用新的 enum class 语法:

enum class VertexType {
   Vector1 = 1,
   Vector2 = 2,
   Vector4 = 3
};

枚举值只能通过 VertexType 类型访问,如 VertexType::Vector1

标准中的一些引述:

§7.2/2 [...] The enum-keys enum class and enum struct are semantically equivalent; an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scoped enumerators. [...]

§7.2/10 [...] Each scoped enumerator is declared in the scope of the enumeration.[...]

// example in §7.2/10
enum class altitude { high=’h’, low=’l’ };
void h() {
  altitude a;        // OK
  a = high;          // error: high not in scope
  a = altitude::low; // OK
}

关于C++ 枚举重新定义和 C++0x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6992593/

相关文章:

c++ - 是否可以使结构直接返回值?

c# - 如何在 .NET C# 3.5 中循环访问 "set"枚举

c++ - 错误 C2678 : binary '+' : no operator found which takes a left-hand operand of type 'volatile A' (or there is no acceptable conversion)

C++11 make_shared 实例化

c++ - 为什么C++全局变量不影响程序的内存使用

c++ - 类型安全的 C++11 枚举类标志模板

c++ - Cplex 随机数 (c++)

c++ - 我可以将 std::move 与不提供 move 构造函数的类一起使用吗?

java - 了解 JNI 参数的安全访问

c++ - 制作大表时程序停止工作(2'000' 000+)