Initialize enum c ++

I am creating an enum named Types


enum  Types {Int,Double,String};  


When I create an object and initialize it to one of the valid enum values, I get the following error: "Error: Type name not allowed."

Types ty = Types.Double;  


Any ideas?


source to share

4 answers

There are two different types of enums in C ++ - scoped and non-scoped (the first was introduced with C ++ 11). For unregistered names, counter names are directly entered into the enclosing area.

N3337 ยง7.2 / 10

Every enumeration name and every unenumerated counter is declared which immediately contains an enumeration specifier. Each enumerator scope is declared in the enumeration scope. These names obey the scoping rules defined for all names in (3.3) and (3.4).

Your listing is not available, so just write

Types ty = Double;


For numbered scopes, as the name suggests, enums are declared in the enumeration scope and must 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;





Types ty = Double;  



enum  class Types {Int,Double,String};  
Types ty = Types::Double;  




In fact it is

Types ty = Double


If you want to cover your values โ€‹โ€‹use the enum class (C ++ 11)

enum class Types {Int,Double,String};


And you can do

Types ty = Types::Double




The compiler is complaining about trying to assign a value Double

, which is the Java way of doing this.

Just do

Types ty = Double;




All Articles