C++ 速查手冊
7.2 - 列舉
列舉是一組整數常數,例如
#include <iostream>
int main() {
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
std::cout << "Sunday: " << Sunday << std::endl;
std::cout << "Monday: " << Monday << std::endl;
std::cout << "Tuesday: " << Tuesday << std::endl;
std::cout << "Wednesday: " << Wednesday << std::endl;
std::cout << "Thursday: " << Thursday << std::endl;
std::cout << "Friday: " << Friday << std::endl;
std::cout << "Saturday: " << Saturday << std::endl;
Day today = Wednesday;
std::cout << today << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u0702_1.cpp
功能:示範 C++ 的列舉型態
作者:張凱慶*/
第 4 行,定義一個列舉型態 Day ,使用關鍵字 (keyword) enum ,後面接著型態名稱 Day ,然後大括弧中是列舉的識別字 (identifier) ,這被稱為非作用域列舉 (unscoped enumeration)
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
列舉常數為從 0 開始遞增的整數常數數列,因此第 30 行宣告的 today 亦為整數常數, Wednesday 是第 4 個值,所以是整數 3
Day today = Wednesday;
編譯執行,結果如下
$ g++ u0702_1.cpp |
$ ./a.out |
Sunday: 0 |
Monday: 1 |
Tuesday: 2 |
Wednesday: 3 |
Thursday: 4 |
Friday: 5 |
Saturday: 6 |
Today: 3 |
$ |
列舉也可以匿名 (anonymous) 與指定起始整數,例如
#include <iostream>
int main() {
enum {apple, banana = 11, orange, peach = 5};
std::cout << "apple: " << apple << std::endl;
std::cout << "banana: " << banana << std::endl;
std::cout << "orange: " << orange << std::endl;
std::cout << "peach: " << peach << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u0702_2.cpp
功能:示範 C++ 的列舉型態
作者:張凱慶*/
此例的列舉沒有識別字,另外將 banana 設定為 11 ,因此 orange 就由 11 遞增為 12 ,最後的 peach 則設定為 5
enum {apple, banana = 11, orange, peach = 5};
編譯後執行,結果如下
$ g++ u0702_2.cpp |
$ ./a.out |
apple: 0 |
banana: 11 |
orange: 12 |
peach: 5 |
$ |
列舉也可以跟 struct 或 class 一起宣告,形成作用域列舉 (scoped enumeration) ,例如
enum class Color {RED, GREEN, BLUE};
C++11 中,列舉常數可以改用其他型態,此時要在列舉識別字後面加上冒號及型態名稱,舉例如下
#include <iostream>
enum class Color: char {
RED = 'r',
GREEN = 'g',
BLUE = 'b',
};
int main() {
Color r;
r = Color::RED;
Color g;
g = Color::GREEN;
Color b;
b = Color::BLUE;
std::cout << "RED: " << static_cast<char>(r) << std::endl;
std::cout << "GREEN: " << static_cast<char>(g) << std::endl;
std::cout << "BLUE: " << static_cast<char>(b) << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u0702_3.cpp
功能:示範 C++ 的列舉型態
作者:張凱慶*/
這裡定義一個作用域列舉,並且將列舉常數的型態指定為 char
enum class Color: char {
RED = 'r',
GREEN = 'g',
BLUE = 'b',
};
編譯後執行,結果如下
$ g++ u0702_3.cpp -std=c++0x |
$ ./a.out |
RED: r |
GREEN: g |
BLUE: b |
$ |
相關教學影片