當變數只能取有限幾個離散值時,enum 讓你為每個值賦予有意義的名稱,提升可讀性與型別安全。編譯器將列舉元素視為**整數常數**。
// 1. 先定義類型,再宣告變數
enum Box { Pencil, Pen };
Box myBox; // C++ 風格
enum Box myBox2; // C 風格
// 2. 定義同時宣告
enum { Pencil, Pen } box, box2;
// 3. C++11 強型別列舉(推薦)
enum class Color { Red, Green, Blue }; // 作用域隔離,無隱式轉 int
Color c = Color::Red; // 需加作用域
// int x = c; // 錯誤:需 static_cast<int>(c)
Pencil=0, Pen=1。enum Box { Pencil=1, Pen=2 }。enum Box { Pencil=3, Pen } → Pen=4(接前者 +1)。enum { A=0, B=0, C=1 }(不同名稱同值)。enum Box { Pencil, Pen };
// Pencil = 1; // 編譯錯誤:列舉元素為常數,非左值
enum Egg { A, B, C };
Egg test = C; // 合法:賦予列舉元素
if (test == C) { ... } // 合法:與列舉元素比較
if (test == 2) { ... } // 合法:隱式轉 int 比較(C++ 隱式允許,C++11 enum class 禁止)
// 錯誤:直接賦整數
// test = 1; // C++ 錯誤,C 允許但有警告
// 正確:強制轉型
test = static_cast<Egg>(0); // 或 (Egg)0
在算術運算語境,列舉元素自動提升為 int:
enum Test { A, B };
int c = 1 + B; // B 提升為 1,c = 2
enum Flags {
Read = 1 << 0, // 1
Write = 1 << 1, // 2
Exec = 1 << 2 // 4
};
int perm = Read | Write; // 3
if (perm & Write) { ... }
class File {
enum class Mode { Read, Write, Append };
Mode mode;
public:
void open(Mode m) { mode = m; /* ... */ }
};
// 呼叫:file.open(File::Mode::Read);
const char* to_string(Color c) {
switch (c) {
case Color::Red: return "Red";
case Color::Green: return "Green";
case Color::Blue: return "Blue";
}
return "Unknown";
}
enum 是表達「有限離散值集合」的利器。傳統 enum 隱式轉 int 方便但易混淆;C++11 enum class 提供強型別隔離、作用域封裝、底層類型指定(enum class Flag : uint8_t),**新代碼強烈建議預設使用 enum class**,僅在需與 C API/位元運算互通時用傳統 enum。