枚舉類(「新枚舉」,「強枚舉」)解決三個問題,與傳統的C++枚舉:
- 傳統
enums
隱式轉換爲int
,導致錯誤,當有人不希望的枚舉作爲一個整數。
- 傳統
enums
將他們的統計員輸出到周圍的範圍,導致姓名衝突。
- 無法指定
enum
的基礎類型,導致混淆,兼容性問題,並且使前向聲明變得不可能。
enum class
(「強枚舉」)是強類型和範圍的:
enum Alert { green, yellow, orange, red }; // traditional enum
enum class Color { red, blue }; // scoped and strongly typed enum
// no export of enumerator names into enclosing scope
// no implicit conversion to int
enum class TrafficLight { red, yellow, green };
Alert a = 7; // error (as ever in C++)
Color c = 7; // error: no int->Color conversion
int a2 = red; // ok: Alert->int conversion
int a3 = Alert::red; // error in C++98; ok in C++11
int a4 = blue; // error: blue not in scope
int a5 = Color::blue; // error: not Color->int conversion
Color a6 = Color::blue; // ok
如圖所示,傳統枚舉照常上班,但你現在可以選擇用枚舉的名字資格。
新的枚舉類型是「枚舉類」,因爲它們將傳統枚舉(名稱值)的方面與類的方面(作用域成員和沒有轉換)相結合。
能夠指定的基本類型允許枚舉的簡單的互操作性和保證尺寸:枚舉
enum class Color : char { red, blue }; // compact representation
enum class TrafficLight { red, yellow, green }; // by default, the underlying type is int
enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // how big is an E?
// (whatever the old rules say;
// i.e. "implementation defined")
enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U }; // now we can be specific
這也使前向聲明:
enum class Color_code : char; // (forward) declaration
void foobar(Color_code* p); // use of forward declaration
// ...
enum class Color_code : char { red, yellow, green, blue }; // definition
基礎類型必須是一個有符號或無符號整數類型;默認爲int
。
在標準庫,enum
類用於:
- 映射系統特定的錯誤代碼:在
<system_error>
:enum class errc
;
- 指針安全指標:
<memory>
:enum class pointer_safety { relaxed, preferred, strict };
- I/O流誤區:
<iosfwd>
:enum class io_errc { stream = 1 };
- 異步通訊錯誤處理:在
<future>
:enum class future_errc { broken_promise, future_already_retrieved, promise_already_satisfied };
其中幾個已運營商,如==
定義。
您是否曾瀏覽[wikipedia](http://en.wikipedia.org/wiki/C%2B%2B11#Strongly_typed_enumerations)? – Nobody
@Nobody:是的,我看過'wiki',但無法理解如何使用它,以及有什麼好處。 –