enum与int的相互转换

如何正确理解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类型有意义。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章