枚举 vs 强类型枚举

2021-12-29 00:00:00 enums c++ c++11

我是 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.

相关文章