9.15 Unscoped enumeration input and output

주홍영·2022년 3월 14일
0

Learncpp.com

목록 보기
106/199

https://www.learncpp.com/cpp-tutorial/unscoped-enumeration-input-and-output/

실제로 enum type의 내부 변수는 integer value를 가진다

#include <iostream>

enum Color
{
    black, // assigned 0
    red, // assigned 1
    blue, // assigned 2
    green, // assigned 3
    white, // assigned 4
    cyan, // assigned 5
    yellow, // assigned 6
    magenta // assigned 7
};

int main()
{
    Color shirt{ blue }; // This actually stores the integral value 2

    return 0;
}

그리고 explicit하게 value를 설정할 수도 있다

enum Animal
{
    cat = -3,
    dog,         // assigned -2
    pig,         // assigned -1
    horse = 5,
    giraffe = 5, // shares same value as horse
    chicken      // assigned 6
};

위 코드에서 horse와 giraffe는 똑 같은 value를 가지고 있다.
c++ 에서 이를 허용하기는 하지만 이는 피해야할 사항이다

그리고 굳이 특별한 목적이 있지 않는 한 그냥 explict하게 value를 설정하지 않고
default 세팅으로 사용하는 것이 좋다

Enumeration size and base

기본적으로 enum variable은 int와 같은 크기를 가지고 있다
하지만 programmer가 직접 설정할 수 도 있다

// Use an 8-bit unsigned integer as the enum base
enum Color : std::uint8_t
{
    black,
    red,
    blue,
};

8-bit uint를 위와 같이 설정해서 사용할 수도 잇따

Integer to unscoped enumerator conversion

enum variable은 int로 initialize 할 수 없다
int 형 value로 pet으로 conversion 또한 불가능하다

#include <iostream>

enum Pet
{
    cat, // assigned 0
    dog, // assigned 1
    pig, // assigned 2
    whale, // assigned 3
};

int main()
{
    Pet pet { 2 }; // compile error: integer value 2 won't implicitly convert to a Pet
    pet = 3;       // compile error: integer value 1 won't implicitly convert to a Pet

    return 0;
}

정말로 어쩔 수 없이 하고 싶다면 static_cast를 통하는 방법이 있다

#include <iostream>

enum Pet
{
    cat, // assigned 0
    dog, // assigned 1
    pig, // assigned 2
    whale, // assigned 3
};

int main()
{
    Pet pet { static_cast<Pet>(2) }; // convert integer 2 to a Pet
    pet = static_cast<Pet>(3);       // our pig evolved into a whale!

    return 0;
}
profile
청룡동거주민

0개의 댓글