初始化枚举 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25831622/
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
Initialize enum c++
提问by user3165438
I create an enum called Types
:
我创建了一个名为的枚举Types
:
enum Types {Int,Double,String};
When I create an object and initialize it with one of the enum allowed values I get the following error: "Error: type name is not allowed".
当我创建一个对象并使用枚举允许的值之一对其进行初始化时,我收到以下错误:“错误:不允许类型名称”。
Types ty = Types.Double;
Any ideas?
有任何想法吗?
回答by Columbo
In C++, there are two different types of enumerations - scoped and unscoped ones (the former was introduced with C++11). For unscoped ones the names of the enumerators are directly introduced into the enclosing scope.
在 C++ 中,有两种不同类型的枚举 - 有作用域的和无作用域的(前者是在 C++11 中引入的)。对于无作用域的,枚举器的名称直接引入封闭作用域。
N3337 §7.2/10
Each enum-nameand each unscoped enumeratoris declared in the scope that immediately contains the enum-specifier. Each scoped enumeratoris declared in the scope of the enumeration. These names obey the scope rules defined for all names in (3.3) and (3.4).
N3337 §7.2/10
每个enum-name和每个无作用域枚举器都在立即包含enum-specifier的作用域中声明。每个作用域 枚举器都在枚举的作用域中声明。这些名称遵守为 (3.3) 和 (3.4) 中的所有名称定义的范围规则。
Your enumeration is unscoped, therefore it suffices to write
您的枚举是无作用域的,因此只需编写
Types ty = Double;
For scoped enumerations, as the name suggests, the enumerators are declared in the enumeration scope and have to be qualified with the enumeration-name:
对于有作用域的枚举,顾名思义,枚举器是在枚举作用域中声明的,并且必须用枚举名称进行限定:
enum class ScopedTypes {Int,Double,String};
enum UnscopedTypes {Int,Double,String};
ScopedTypes a = ScopedTypes::Double;
//ScopedTypes b = Double; // error
UnscopedTypes c = UnscopedTypes::Double;
UnscopedTypes d = Double;
回答by Vlad from Moscow
Either use
要么使用
Types ty = Double;
or
或者
enum class Types {Int,Double,String};
Types ty = Types::Double;
回答by Code-Apprentice
The compiler is complaining about the attempt at qualifying the value Double
which is Java's way to do this.
编译器抱怨试图限定值Double
,这是 Java 执行此操作的方式。
Just do
做就是了
Types ty = Double;