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
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
