HR's Blog

Swimming 🏊 in the sea🌊of code!

0%

enumerations

.

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
2
3
4
5
6
7
8
9
10
11
enum card_suit : uint8_t { SPD, HRT, DIA, CLB };
enum card_rank : uint8_t { ACE = 1, DEUCE = 2, JACK = 11, QUEEN, KING }; //QUEEN 12 King 13. because by definition, they go sequentially from the last specified number.会连续到最后一个值。

enum Traffic_light { red, yellow, green };
enum Warning { green, yellow, orange, red};

Warning a1 = 7; //错误
int a1 = green; //可以
int a2 = red; //错误,在现在的范围内存在两个Red,需要指明Warning::red
int a3 = Warning::green;
Warning a4 = Warning::green;

Enum classes

1
2
3
4
5
6
7
enum class Traffic_light { red, yellow, green};
enum class Warning { green, yellow, orange, red};

Warning a1 = 7; //不能隐性转换
int a2 = green; //gree不在范围内
int a3 = Warning::green; //不能隐性转换
Warning a4 = Warning::green; //可以

enum class默认的值是从0开始

显性转换enum class的值

1
2
static_cast<int>(Warning::green) == 0
Warning values = static_cast<Warning>(0) //Warning::green

自定义枚举的值

1
2
3
4
enum class Printer_flags {
acknowledge = 1,
paper_empty = 2,
}