Enum vs Strongly typed enum(枚举 vs 强类型枚举)
问题描述
我是 C++ 编程的初学者.
I am a beginner in C++ programming.
今天我遇到了一个新话题:强类型enum
.我已经对它进行了一些研究,但直到现在我无法弄清楚为什么我们需要它以及它的用途是什么?
Today I come across a new topic: strongly typed enum
. I've researched it a bit but till now I am unable to find out why do we need this and what is the use of the same?
例如,如果我们有:
enum xyz{a, b, c};
/*a = 0, b = 1, c = 2, (Typical C format)*/
为什么我们需要写:
enum class xyz{a, b, c};
我们在这里想做什么?我最重要的疑问是如何使用它.能否举个小例子,让我明白.
What are we trying to do here? My most important doubt is how to use it. Could you provide a small example, which will make me understand.
推荐答案
好的,第一个例子:旧式枚举没有自己的作用域:
OK, first example: old-style enums do not have their own scope:
enum Animals {Bear, Cat, Chicken};
enum Birds {Eagle, Duck, Chicken}; // error! Chicken has already been declared!
enum class Fruits { Apple, Pear, Orange };
enum class Colours { Blue, White, Orange }; // no problem!
其次,它们隐式地转换为整型,这会导致奇怪的行为:
Second, they implicitly convert to integral types, which can lead to strange behaviour:
bool b = Bear && Duck; // what?
最后,您可以指定 C++11 枚举的底层整数类型:
Finally, you can specify the underlying integral type of C++11 enums:
enum class Foo : char { A, B, C};
之前没有指定底层类型,这可能会导致平台之间的兼容性问题.编辑 在注释中已经指出,您还可以在 C++11 中指定旧式"枚举的底层整数类型.
Previously, the underlying type was not specified, which could cause compatibility problems between platforms. Edit It has been pointed out in comments that you can also specify the underlying integral type of an "old style" enum in C++11.
这篇关于枚举 vs 强类型枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:枚举 vs 强类型枚举


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05