C ++在类中声明静态枚举与枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28707388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:02:22  来源:igfitidea点击:

C++ declaring static enum vs enum in a class

c++classenumsstaticnested

提问by user3731622

What's the difference between the static enumand enumdefinitions when defined inside a class declaration like the one shown below?

在如下所示的类声明中定义时static enumenum定义之间有什么区别?

class Example
{
     Example();
     ~Example();

     static enum Items{ desk = 0, chair, monitor };
     enum Colors{ red = 0, blue, green };
}

Also, since we are defining types in a class, what do we call them? By analogy if I define a variable in a class, we call it a member variable.

另外,由于我们在类中定义类型,我们称它们为什么?以此类推,如果我在类中定义一个变量,我们称它为成员变量。

采纳答案by Praetorian

staticcannot be applied to enumdeclarations, so your code is invalid.

static不能应用于enum声明,因此您的代码无效。

From N3337, §7.1.1/5 [dcl.stc]

来自 N3337,§7.1.1/5 [dcl.stc]

The staticspecifier can be applied only to names of variables and functions and to anonymous unions ...

static说明符只能应用到的变量和函数的名称,并以匿名联合...

An enumdeclaration is none of those.

enum声明是没有这些的。

You can create an instance of the enumand make that staticif you want.

您可以创建 的实例enum并根据static需要进行创建。

class Example
{
     enum Items{ desk = 0, chair, monitor };
     static Items items; // this is legal
};

In this case itemsis just like any other static data member.

在这种情况下items就像任何其他静态数据成员一样



This is an MSVC bug; from the linked bug report it seems the compiler will allow both staticand registerstorage specifiers on enumdeclarations. The bug has been closed as fixed, so maybe the fix will be available in VS2015.

这是一个MSVC 错误;从链接的错误报告看来,编译器将允许在声明中同时使用staticregister存储说明符enum。该错误已作为修复关闭,因此该修复可能会在 VS2015 中可用。

回答by Marcus Müller

staticis a C++ storage specifier. It means the value of this member of the class is the same for all instances of the class. Nothing special about enums here.

static是 C++ 存储说明符。这意味着该类的该成员的值对于该类的所有实例都是相同的。这里的枚举没有什么特别之处。

EDIT: Even the statictag wiki has an explanation. On exactly this topic.

编辑:即使是static标签维基也有解释。正好在这个话题上。

EDIT2: Oh, I've misread your code. There's no static enum. You can have a static variable of an enum type that holds a value.

EDIT2:哦,我误读了你的代码。没有静态枚举。您可以拥有一个包含值的枚举类型的静态变量。