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.
这篇关于为什么枚举类比普通枚举更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么枚举类比普通枚举更受欢迎?
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
