Modern C++ - enum class

이승덱·2021년 7월 21일

CPP

목록 보기
64/70
#include <iostream>

#include <vector>

#include <list>

#include <deque>

#include <map>

#include <set>

#include<algorithm>

using namespace std;

// Modern C++ (C++11 부터 나온 아이들)

// enum class (scoped enum)

// 1) 이름 공간 관리 (scoped)

// 2) 암묵적인 변환 금지 (장점이 될 수도 단점이 될 수도 있음)

// enum의 특징

// 기본적으로 int로 잡힘

// 암묵적으로 대응하는 숫자를 지정해줌

// unscoped enum 범위가 지정되지 않음(여기서 선언되는 이름은 다른 enum에서 사용이 될 수 없음.)

enum PlayerType /* : char 데이터형 지정할 수도 있다*/{

 None, 

 PT_Knight,

 PT_Archer,

 PT_Mage,

};

enum MonsterType {

 //None, //enum으로는 중복되는 이름 사용 불가

};

// enum class (scoped enum)

// 1) 이름 공간 관리 (scoped)

// 2) 암묵적인 변환 금지 (장점이 될 수도 단점이 될 수도 있음)

enum class ObjectType {

 Player,

 Monster,

 Projectile,

};

enum class ObjectType2 {

 Player,

 Monster,

 Projectile,

 // scoped enum 다른 enum class에서 사용된 이름도 재활용이 가능 

};

int main()

{

 double value = PT_Archer; //암묵적으로 변환

 double value2 =static_cast<double>(ObjectType::Player); //암묵적인 변환이 안됨

 int choice = 1;

 // 간-편

 if (choice == PT_Knight) {

 }

 // 불-편

 if (choice == static_cast<int>(ObjectType::Monster)) {

 }

 unsigned int bitFlag;

 bitFlag = (1 << static_cast<int>(ObjectType::Player));

 return 0;

}
profile
공부 기록용 블로그입니다

0개의 댓글