3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

enumとenum class

Posted at

enum

sampleEnum.cpp
enum SampleEnum : int
{
    se1,
    se2
};

void Function()
{
    auto val1=se1;    
    auto val2=SampleEnum::se2;
    std::cout << "val1:" << val1 << ",val2:" << val2 << std::endl; 
}
  • スコープを持たない列挙型
  • 暗黙的にint型になる

enum class

sampleEnumClass.cpp
enum class SampleEnumClass : int
{
    sec1,
    sec2
};


void Function(){
    // auto val1=sec1;  // !コンパイルエラー
    auto val2=SampleEnumClass::sec2;
    std::cout << "val2:" << static_cast<int>(val2) << std::endl; 
}

  • 明示的なキャストが必要になる
  • enum class 名を明示的なスコープとして指定する必要がある

共通すること

  • enum (class) hoge の後に規定型を指定できる
  • 前方宣言ができる

比較

enum enum class
規定型の指定 enum SampleEnum : int ○できる ○できる
前方宣言 enum SampleEnum : int; ○できる ○できる
列挙への直接的なアクセス auto = se1; ○できる ×できない
列挙への直接的なアクセス例 SampleEnum v = se1;
SampleEnum v=SampleEnum:se1;
SampleEnumClass v = SampleEnumClass:sec1;
値をint型としてアクセス int i=v; int i = static_cast<int>(v)
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?