.
An enumeration is a type that can hold a set of integer values specified by the user.
C++中包含两种枚举类型:Plain enums:
枚举值与枚举类型本身在用一个作用域中,枚举值会隐形的转为整数。enum class:
他们枚举的值作用域在枚举的内部,枚举值不会隐式的转为其他的类型。
enum is that while, It looks syntactically like a type, and it’s even referred to as a type, it’s not really a type. Enumerated names actually work more like constants than like types and they make a great alternative to pre-processor constants.
Plain enums
Plain需要注意有可能在当前的范围内存在两个枚举,而两个枚举里面都包含相同值。例如x == red
,编译器是不会报错的。但是red有可能是Traffic_light
或者是Warning
里面的。
1 | enum card_suit : uint8_t { SPD, HRT, DIA, CLB }; |
Enum classes
1 | enum class Traffic_light { red, yellow, green}; |
enum class
默认的值是从0开始
显性转换enum class
的值
1 | static_cast<int>(Warning::green) == 0 |
自定义枚举的值
1 | enum class Printer_flags { |