HUX布斯
C+有两种enum:enum class埃斯平原enums下面是几个如何声明它们的示例: enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum两者有什么区别?enum class枚举数名称为本土化对于枚举和它们的值不隐式转换为其他类型(类似于另一种类型)enum或int)平原enums-其中枚举数名称与枚举的作用域相同,它们的值隐式转换为整数和其他类型。例子:enum Color { red, green, blue };
// plain enum enum Card { red_card, green_card, yellow_card };
// another plain enum enum class Animal { dog, deer, cat, bird, human };
// enum classenum class Mammal { kangaroo, deer, human };
// another enum classvoid fun() {
// examples of bad use of plain enums:
Color color = Color::red;
Card card = Card::green_card;
int num = color; // no problem
if (color == Card::red_card) // no problem (bad)
cout << "bad" << endl;
if (card == Color::green) // no problem (bad)
cout << "bad" << endl;
// examples of good use of enum classes (safe)
Animal a = Animal::deer;
Mammal m = Mammal::deer;
int num2 = a; // error
if (m == a) // error (good)
cout << "bad" << endl;
if (a == Mammal::deer) // error (good)
cout << "bad" << endl;}结论:enum classES应该是首选的,因为它们会带来更少的可能导致bug的惊喜。