Reputation: 3121
Hi I have files called MyCode.h and MyCode.cpp
In MyCode.h I have 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 'MyEnum' is not a class or namespace...
(works fine in MS VS2010 but not linux g++)
Any ideas? Thanks Thomas
Upvotes: 62
Views: 55808
Reputation: 883
As explain in other answers: syntax MyEnum::SomethingElse
is not valid on regular C++98 enums unless your compiler supports them through non-standard extensions.
I personally don't like the declaration enum MyEnum {A, B};
because Type name is not present while using enum values. This can leads to conflict of names in the current name space.
So user should refer to the type name at each enum values. 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 name space or structure. This allow to reference enum values with latest C++ style:
namespace MyEnum {
enum Value {A,B};
}
void A(void) {
MyEnum::Value enumInstance = MyEnum::A
}
Upvotes: 2
Reputation: 1774
Indeed, C++0x allows that feature. I could enable it successfully in gcc using this command line flag: -std=c++0x
This was with gcc version 4.4.5
Upvotes: 31
Reputation: 20031
The syntax MyEnum::SomethingElse
is a Microsoft extension. It happens to be one I like, but it's not Standard C++. 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;
}
Upvotes: 68
Reputation: 62975
Scoped enums will not exist until C++0x. For the time being, your code should be
enumInstance = SomethingElse;
You can create an artificial scoped enum by putting the enum's definition inside its own namespace or struct.
Upvotes: 51