c++ - 枚举 [标签] [ : type] {enum-list} [declarator] in C++ - is this legal?

标签 c++ visual-studio enums enumeration

我正在使用 C++ 中的自定义枚举类型,但它没有很多值。我想尝试减小它们占用的大小,而且我听说 enum 类型是 always integers by default .然后我遇到了 MSDN entry on C++ enumerations , 发现下面的语法很有趣:

enum [: type] {enum-list};

果然,当我执行以下操作时,它编译出了我想要的 (VS2008):

enum plane : unsigned char { xy, xz, yz };

现在,您可以从我的枚举常量中看出我不需要太多空间 - unsigned char 类型非常适合我的使用。

但是,我不得不说,我从未在互联网上的其他地方任何地方见过这种形式——大多数人甚至似乎都没有意识到这一点。我正在尝试使这段代码跨平台(并且可能用于嵌入式系统),所以这让我想知道...这是正确的 C++ 语法,还是仅受 MSVC 编译器支持?

编辑:似乎这个特性现在是C++11及以上版本的一部分,叫做scoped enumerations .

最佳答案

这是非标准的,但它有望成为 C++0x 标准的一部分。对我来说,当我在 Visual Studio 2005 中编译时将警告级别设置为最大,我收到以下警告:

警告 C4480:使用了非标准扩展:为枚举“Test”指定基础类型

来自Wikipedia page for C++0x :

In standard C++, enumerations are not type-safe. They are effectively integers, even when the enumeration types are distinct. This allows the comparison between two enum values of different enumeration types. The only safety that C++03 provides is that an integer or a value of one enum type does not convert implicitly to another enum type. Additionally, the underlying integral type is implementation-defined; code that depends on the size of the enumeration is therefore non-portable. Lastly, enumeration values are scoped to the enclosing scope. Thus, it is not possible for two separate enumerations to have matching member names.

Additionally, C++0x will allow standard enumerations to provide explicit scoping as well as the definition of the underlying type:

enum Enum3 : unsigned long {Val1 = 1, Val2};

关于c++ - 枚举 [标签] [ : type] {enum-list} [declarator] in C++ - is this legal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6741059/

相关文章:

c++ - 从 std::vector<cv::Point>::const_iterator 检索值

c++ - ChangeDisplaySettings(NULL, 0) 移动/调整我的窗口

java - 如何访问数组的枚举

c++ - 如何在 C++ 中使用枚举类型?

ios - Swift 3.0 - 根据 2 个不同枚举的每种情况调用函数

c++ - Jetson TK1 - 嵌入式 Linux - 如何定期中断

visual-studio - Visual Studio 2012 Debug模式下的 "Unable to evaluate the expression"

c++ - 如何检测类中是否存在特定的成员变量?

c++ - 如何使用 Visual C++ 中的 Delphi 寄存器调用约定调用函数?

c++ - 将成员访问运算符与重载调用运算符相结合