My listing is not a class or namespace

Hi I have files named MyCode.h and MyCode.cpp

In MyCode.h I declared

enum MyEnum {Something = 0, SomethingElse = 1}; class MyClass { MyEnum enumInstance; void Foo(); }; 

Then in MyCode.cpp:

 #include "MyCode.h" void MyClass::Foo() { enumInstance = MyEnum::SomethingElse; } 

but when compiling with g ++, I get the error message "MyEnum" is not a class or namespace ...

(works fine in MS VS2010, but not linux g ++)

Any ideas? thanks Thomas

+55
c ++ enums c ++ 11 g ++
04 Mar. 2018-11-11T00:
source share
4 answers

Syntax MyEnum::SomethingElse is a Microsoft extension. This is one of the ones I like, but it is not a C ++ standard. enum values ​​are added to the surrounding namespace:

  // header enum MyEnum {Something = 0, SomethingElse = 1}; class MyClass { MyEnum enumInstance; void Foo(); } // implementation #include "MyClass.h" void Foo() { enumInstance = SomethingElse; } 
+56
Mar 04 '11 at 1:15
source share

The copied enums will not exist until C ++ 0x. For now, your code should be

 enumInstance = SomethingElse; 

You can create an artificial enumeration cloud by placing the enumeration definition inside your own namespace or structure.

+51
Mar 04 2018-11-11T00:
source share

Indeed, C ++ 0x allows this function. I can enable it successfully in gcc using this command line flag: -std = C ++ 0x

It was with gcc version 4.4.5

+29
Sep 12 2018-11-11T00:
source share

As other answers explain: MyEnum::SomethingElse syntax is MyEnum::SomethingElse valid for regular C ++ 98 lists if your compiler does not support them through non-standard extensions.

I personally do not like the ad enum MyEnum {A, B}; because the type name is missing when using enum values. This can lead to a name conflict in the current namespace.

Thus, the user must refer to the type name for each value of the enumeration. Example to avoid declaring A twice:

 enum MyEnum {MyEnum_A, MyEnum_B}; void A(void) { MyEnum enumInstance = MyEnum_A; } 

I prefer to use a specific namespace or structure. This allows you to reference enum values ​​with the latest C ++ style:

 namespace MyEnum { enum Value {A,B}; } void A(void) { MyEnum::Value enumInstance = MyEnum::A } 
+2
Nov 06 '15 at 10:48
source share



All Articles