[ VC11-C++11 ] enum - unscoped enumeration과 scoped enumeration

C++0x 2012. 7. 16. 09:00 Posted by 알 수 없는 사용자

C++11(새로운 C++ 표준의 이름) enum은 지금(C++03)과 다르게 두 가지의 enum이 있습니다.

바로 unscoped enumerationscoped enumeration 입니다.

 

 

unscoped enumeration

unscoped enumeration은 기존의 enum과 비슷한 것 이라고 생각 하면 좋을 것 같습니다.^^

 

 

unscoped enumeration은 아래와 같이 정의하고 사용합니다.

 

enum ITEMTYPE : short

{

   WEAPON,

   EQUIPMENT,

   GEM       = 10,

   DEFENSE,      // C++03까지는 에러이지만 C++11에서는 에러가 아님

};

 

사용은 아래와 같이

short ItemType = WEAPON;

 또는

short ItemType = ITEMTYPE::WEAPON; // C++03에서는 에러

 

 


scoped enumeration 

scoped enumeration은 아래와 같이 정의하고 사용합니다.

enum class CHARACTER_CLASS : short

{

           WARRIOR                    = 1,     

           MONK,

           FIGHTER,

};

 

사용은 아래와 같이 합니다.

CHARACTER_CLASS CharClass = CHARACTER_CLASS::WARRIOR;

 

그러나 아래는 에러입니다.

short CharClassType = FIGHTER; // 에러

 

scoped enumeration unscoped enumeration와 다르게 CHARACTER_CLASS를 생략하면 안됩니다. WARRIOR 이나 MONKCHARACTER_CLASS의 범위 안에 있음을 가리킵니다.

 

그리고 enum class 대신 enum struct을 사용해도 괜찮습니다. 타입을 지정하지 않으면 기본으로 int 타입이 됩니다.

 

 

 

형 변환

unscoped enumeration은 기존과 같이 암묵적으로 정수로 변환할 수 있습니다.

int i = WEAPON;

 

그러나 scoped enumeration은 명시적으로 타입 캐스팅을 해야합니다.

int i = static_cast<int>( CHARACTER_CLASS::WARRIOR);

 

 

 

< 예제 >

#include <iostream>

 

// unscoped enumeration

enum ITEMTYPE : short

{

           WEAPON,

           EQUIPMENT,

           GEM                          = 10,

           DEFENSE,

};

 

// scoped enumeration

enum class CHARACTER_CLASS : short

{

           WARRIOR                    = 1,     

           MONK,

           FIGHTER,

};

 

enum struct BATTLE_TYPE : short

{

           DEATH_MATCH              = 1,     

           TEAM,

};

 

int main()

{

           // unscoped enumeration

           std::cout << "ITEM WEAPON Type 번호 : " << ITEMTYPE::WEAPON << std::endl;

 

           short ItemType = EQUIPMENT;

           std::cout << "ITEM EQUIPMENT Type 번호 : " << ItemType << std::endl;

 

 

 

           /// scoped enumerations

           short CharClassType3 = (short)CHARACTER_CLASS::FIGHTER;

 

           CHARACTER_CLASS CharClass = CHARACTER_CLASS::WARRIOR;

          

           //short   CharClassType    = FIGHTER;                                  // 에러                                           

 

           //short   CharClassType2   = CHARACTER_CLASS::FIGHTER; // 에러

          

           //CHARACTER_CLASS       CharClass2    = WARRIOR;            // 에러

                            

           return 0;

}