列挙型

 

 

 

1. 基本説明

 

[環境]

コンパイラ : g++ (Ubuntu 13.3.0-6ubuntu2~24.04), 13.3.0
OS : Ubuntu 24.04, WSL

 

列挙型は、名前付きの定数として扱える列挙子の集合を表現する型です。「種別」や「状態」といった有限を定義したい場合に使用することで可読性が向上します。

また、列挙型は代入する値を定義した範囲に制限できるため、定数や #define 定義を使用した場合と比べて安全に扱うことができます。

 

コード例: "enumeration_01.cpp"

#include <iostream>

int main() {
    enum TrafficLight { Blue, Yellow, Red };
    TrafficLight light = Blue;

    std::cout << "TrafficLight: " << static_cast<int>(light) << std::endl;

    return 0;
}

 

ビルド・実行例:

$ g++ -Wall enumerator_01.cpp -o enumerator_01.out
$ ./enumerator_01.out 
TrafficLight: 0
$

 

 

上記例では、交通信号機の色と状態を表す列挙型として以下のように定義しています。

enum TrafficLight { Blue, Yellow, Red };
TrafficLight light = Blue;

 

列挙型の各列挙子は、無指定だと 0から順に1ずつ増加した値となります。

列挙型の各列挙子を任意の値にするためには、= で列挙子の値を定義します。以下は、= を使って列挙型の各列挙子を任意の値に設定する例です。

enum TrafficLight { Blue = 1, Yellow = 3, Red };

この例では、Blue が 1、Yellow が 3、Red が 4 となります。

 

また、型名で修飾して TrafficLight::Blue のように記述もできます。

enum TrafficLight { Blue, Yellow, Red };
TrafficLight light = TrafficLight::Blue;

 

 

ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

  Copyright 2025 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

参考

 


 

変更履歴

2025-09-24 - 新規作成

 

Programming Items トップページ

プライバシーポリシー