什么是枚举类,为什么要关心? [英] What's an enum class and why should I care?
问题描述
什么是枚举类,为什么需要它?
枚举类
被称为范围枚举。它可以防止枚举出现的命名空间与枚举器的名称。
在C ++ 03中,您可以通过将 enum
在一个专门的类
中。也许这是语法的来源,这有点混乱。
另一个区别是这种类型的枚举器不会隐式转换为 int
( static_cast< int>
是必需的)。这可能很少需要,但它可以安全地重载一个使用 int
参数的函数,一个取$ 类型。您可以确定不会意外调用
int
。或者您可以使用专用的运算符
函数定义伪整数类型,并确保内置运算符不会干扰。
$ b $这有点令人讨厌,这两个不相关的差异在同一个包中,并且您无法获得没有隐式转换的枚举枚举,但通常这两个更改都是Good Things和
枚举类
是C ++ 11中的一个很好的默认做法。 编辑:范围枚举定义如下:
枚举类duck {huey,dewey,louie};
,必须与范围解析运算符 ::
如下所示:
duck culprit = duck :: huey; //或auto culprit以避免冗余
请注意,
运算符也可以使用C ++ 03无范围的枚举,所以上面的第二行即使第一个缺少 class
。
这可能是过多的细节,但 class
不会进入详细说明型的说明符
void quack(enum duck who); //不是enum class
然而,C ++ 11中有一个新构造, opaque-enum-declaration ,其中包含类
关键字并定义完整的类型。
枚举鸭子$ pre>
// duck被声明为不完整的类型
enum class duck; //鸭现在完成类型;底层类型默认为int
关键字 struct
可以代替 class
,没有语义差异。
For one who has never written a line of C++11, and who has, at the moment, no opportunity to program in C++11, can you, in one short paragraph., tell me:
What is an "enum class" and why do we need it?
enum class
is called a scoped enumeration. It prevents polluting the namespace where the enumeration appears with the names of the enumerators.
In C++03, you could do effectively the same thing by putting the enum
inside a dedicated class
. Perhaps that's the source of the syntax, which is a bit confusing.
Another difference is that the enumerators of such a type don't convert implicitly to int
(static_cast<int>
is required). This may be seldom needed but it makes it safe to overload a function taking an int
argument with one taking enum
type. You can be sure the int
won't be called by accident. Or you can define pseudo-integral types with dedicated operator
functions, and be sure that built-in operators won't interfere.
It's a bit annoying that these two unrelated differences come in the same package, and that you can't get an unscoped enumeration with no implicit conversion, but generally both changes are Good Things and enum class
is a good default practice in C++11.
EDIT: A scoped enumeration is defined like this:
enum class duck { huey, dewey, louie };
and must be used with the scope resolution operator ::
like this:
duck culprit = duck::huey; // or "auto culprit" to avoid redundancy
Note that the ::
operator also works with C++03 unscoped enumerations, so the second line above would work even if the first was missing class
.
This might be excessive detail, but class
does not go into the elaborated-type-specifier if forward declaring the enumerated type, as in
void quack( enum duck whom ); // not "enum class"
However, there is a construct new in C++11, the opaque-enum-declaration, which does include the class
keyword and defines a complete type.
enum duck; // duck is declared as incomplete type
enum class duck; // duck is now complete type; underlying type defaults to int
The keyword struct
can be substituted for class
with no semantic difference.
这篇关于什么是枚举类,为什么要关心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!