My enum is not a class or namespace

前端 未结 4 1835
南笙
南笙 2020-12-05 06:14

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 e         


        
相关标签:
4条回答
  • 2020-12-05 06:36

    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;
     }
    
    0 讨论(0)
  • 2020-12-05 06:37

    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
    }
    
    0 讨论(0)
  • 2020-12-05 06:47

    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.

    0 讨论(0)
  • 2020-12-05 06:58

    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

    0 讨论(0)
提交回复
热议问题