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
C++ declaring static enum vs enum in a class
提问by user3731622
What's the difference between the static enum
and enum
definitions when defined inside a class declaration like the one shown below?
在如下所示的类声明中定义时static enum
和enum
定义之间有什么区别?
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
static
cannot be applied to enum
declarations, so your code is invalid.
static
不能应用于enum
声明,因此您的代码无效。
From N3337, §7.1.1/5 [dcl.stc]
来自 N3337,§7.1.1/5 [dcl.stc]
The
static
specifier can be applied only to names of variables and functions and to anonymous unions ...
该
static
说明符只能应用到的变量和函数的名称,并以匿名联合...
An enum
declaration is none of those.
的enum
声明是没有这些的。
You can create an instance of the enum
and make that static
if you want.
您可以创建 的实例enum
并根据static
需要进行创建。
class Example
{
enum Items{ desk = 0, chair, monitor };
static Items items; // this is legal
};
In this case items
is 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 static
and register
storage specifiers on enum
declarations. The bug has been closed as fixed, so maybe the fix will be available in VS2015.
这是一个MSVC 错误;从链接的错误报告看来,编译器将允许在声明中同时使用static
和register
存储说明符enum
。该错误已作为修复关闭,因此该修复可能会在 VS2015 中可用。
回答by Marcus Müller
static
is 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 static
tag 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:哦,我误读了你的代码。没有静态枚举。您可以拥有一个包含值的枚举类型的静态变量。