Programing

내 열거 형은 클래스 또는 네임 스페이스가 아닙니다.

lottogame 2020. 12. 7. 07:43
반응형

내 열거 형은 클래스 또는 네임 스페이스가 아닙니다.


안녕하세요, MyCode.h 및 MyCode.cpp라는 파일이 있습니다.

MyCode.h에서 선언했습니다.

enum MyEnum {Something = 0, SomethingElse = 1};

class MyClass {

MyEnum enumInstance;
void Foo();

}; 

그런 다음 MyCode.cpp에서 :

#include "MyCode.h"

void MyClass::Foo() {
    enumInstance = MyEnum::SomethingElse;
}

하지만 g ++로 컴파일 할 때 'MyEnum'is not a class or namespace ...라는 오류가 발생합니다.

(MS VS2010에서는 잘 작동하지만 Linux g ++에서는 작동하지 않음)

어떤 아이디어? 감사합니다 토마스


구문 MyEnum::SomethingElse은 Microsoft 확장입니다. 내가 좋아하는 것이지만 표준 C ++가 아닙니다. enum값이 주변 네임 스페이스에 추가됩니다.

 // header
 enum MyEnum {Something = 0, SomethingElse = 1};

 class MyClass {

 MyEnum enumInstance;
 void Foo();

 }

 // implementation
 #include "MyClass.h"

 void Foo() {
     enumInstance = SomethingElse;
 }

범위가 지정된 열거 형은 C ++ 0x까지 존재하지 않습니다. 당분간 코드는

enumInstance = SomethingElse;

열거 형의 정의를 자체 네임 스페이스 또는 구조체 안에 넣어 인위적인 범위 열거 형을 만들 수 있습니다.


실제로 C ++ 0x는이 기능을 허용합니다. 다음 명령 줄 플래그를 사용하여 gcc에서 성공적으로 활성화 할 수 있습니다. -std = c ++ 0x

이것은 gcc 버전 4.4.5에서였습니다.


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
}

참고URL : https://stackoverflow.com/questions/5188554/my-enum-is-not-a-class-or-namespace

반응형