[英]define enum inside a struct which is inside a class
I have seen people writing code like this... whats the point of it.. 我见过人们在写这样的代码……这有什么意义。
class Test
{
public:
struct MethodEnum
{
enum Enum
{
Method1,
Method2
};
};
};
In pre-C++11, the labels of enum
are not scoped (which means the labels were accessible without any qualification with the enum
type!). 在C ++ 11之前的版本中,
enum
的标签没有作用域(这意味着可以使用enum
类型对其进行任何访问而无需任何限定!)。 So to make them scoped , programmers wrote those code. 因此,为了使它们具有作用域 ,程序员编写了这些代码。 But in C++11, it is not needed, as you can define scoped-enum, using
enum class
. 但是在C ++ 11中,它不是必需的,因为您可以使用
enum class
定义范围enum class
。
So in C++11, your code would look like this: 因此,在C ++ 11中,您的代码如下所示:
class Test
{
public:
enum class MethodEnum
{
Method1,
Method2
};
};
If there is more than one enumerated type defined in the same scope and two of those enumerated types have enumerations with the same name you get a conflict. 如果在同一范围内定义了多个枚举类型,并且其中两个枚举类型具有相同名称的枚举,则会发生冲突。 This technique puts the names into separate scopes, possibly avoiding such a conflict by putting the names into separate scopes.
该技术将名称放入单独的范围,可以通过将名称放入单独的范围来避免这种冲突。 That way, in member functions of
Test
you'd refer to the enumerators as MethodEnum::Method1
, etc. 这样,在
Test
成员函数中,您可以将枚举数称为MethodEnum::Method1
等。
In C++11 you can get scoped names with enum class
. 在C ++ 11中,您可以使用
enum class
获得作用域名称。
Sometimes, you don't want the enumerators to pollute the surrounding scope; 有时,您不希望枚举数污染周围的范围; for example
例如
enum Colour {
Red,
Yellow,
Orange
};
enum Fruit {
Apple,
Physalis,
Orange // ERROR! already defined
};
Your example is the old-fashioned way to enclose them in a scope; 您的示例是将它们封装在范围内的老式方法; these days, we have scoped enumerations (
enum class
) to do that more conveniently. 如今,我们已经对范围内的枚举(
enum class
)进行了设置,以使其更加方便。
It sets logical (or semantic) linkage between MethodEnum and the enumeration. 它设置MethodEnum与枚举之间的逻辑(或语义)链接。 So for example you can write
所以例如你可以写
switch ( SomeExpression )
{
case Test::MethodEnum::Method1
// do some method1
break;
case Test::MethodEnum::Method2
/ do some method2
break;
default:
std::cout << "There is no such a method" << std::endl;
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.