如何正確理解enum類型?
例如:
- enum Color { red, white, blue};
- Color x;
我們應說x是Color類型的,而不應將x理解成enumeration類型,更不應將其理解成int類型。
我們再看enumeration類型:
- enum Color { red, white, blue};
(C程序員尤其要注意!)
理解此類型的最好的方法是將這個類型的值看成是red, white和blue,而不是簡單將看成int值。
C++編譯器提供了Color到int類型的轉換,上面的red, white和blue的值即為0,1,2,但是,你不應簡單將blue看成是2。blue是Color類型的,可以自動轉換成2,但對於C++編譯器來說,並不存在int到Color的自動轉換!(C編譯則提供了這個轉換)
例如以下代碼說明了Color會自動轉換成int:
- enum Color { red, white, blue };
- void f()
- {
- int n;
- n = red; // change n to 0
- n = white; // change n to 1
- n = blue; // change n to 2
- }
以下代碼也說明了Color會自動轉換成int:
- void f()
- {
- Color x = red;
- Color y = white;
- Color z = blue;
- int n;
- n = x; // change n to 0
- n = y; // change n to 1
- n = z; // change n to 2
- }
但是,C++編譯器並不提供從int轉換成Color的自動轉換:
- void f()
- {
- Color x;
- x = blue; // change x to blue
- x = 2; // compile-time error: can't convert int to Color
- }
若你真的要從int轉換成Color,應提供強制類型轉換:
- void f()
- {
- Color x;
- x = red; // change x to red
- x = Color(1); // change x to white
- x = Color(2); // change x to blue
- x = 2; // compile-time error: can't convert int to Color
- }
但你應保證從int轉換來的Color類型有意義。