问题描述
我听说有些人推荐在 C++ 中使用枚举类,因为它们的类型安全.
I heard a few people recommending to use enum classes in C++ because of their type safety.
但这到底是什么意思?
推荐答案
C++有两种enum
:
枚举类
es- 普通
enum
s
这里有几个关于如何声明它们的例子:
Here are a couple of examples on how to declare them:
enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum
两者有什么区别?
-
enum class
es - 枚举器名称是枚举的本地,并且它们的值不会隐式转换为其他类型(例如另一个enum
或int
)
-
enum class
es - enumerator names are local to the enum and their values do not implicitly convert to other types (like anotherenum
orint
)
Plain enum
s - 其中枚举器名称与枚举及其值隐式转换为整数和其他类型
Plain enum
s - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types
示例:
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 class
enum class Mammal { kangaroo, deer, human }; // another enum class
void 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 class
es 应该是首选,因为它们引起的意外更少,可能导致错误.
Conclusion:
enum class
es should be preferred because they cause fewer surprises that could potentially lead to bugs.
这篇关于为什么枚举类比普通枚举更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!