Why is enum class preferred over plain enum?(为什么枚举类比普通枚举更受欢迎?)
问题描述
我听说有些人推荐在 C++ 中使用枚举类,因为它们的类型安全.
I heard a few people recommending to use enum classes in C++ because of their type safety.
但这到底是什么意思?
推荐答案
C++有两种enum:
枚举类es- 普通
enums
这里有几个关于如何声明它们的例子:
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 classes - 枚举器名称是枚举的本地,并且它们的值不会隐式转换为其他类型(例如另一个enum或int)
-
enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like anotherenumorint)
Plain enums - 其中枚举器名称与枚举及其值隐式转换为整数和其他类型
Plain enums - 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 classes 应该是首选,因为它们引起的意外更少,可能导致错误.
Conclusion:
enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.
这篇关于为什么枚举类比普通枚举更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么枚举类比普通枚举更受欢迎?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
