enum和int的相互转换

来源:互联网 发布:绝对领域 知乎 编辑:程序博客网 时间:2024/04/23 14:46

例如:

[cpp] view plaincopy
  1. enum Color { red, white, blue};   
  2. Color x;  


我们应说x是Color类型的,而不应将x理解成enumeration类型,更不应将其理解成int类型。

 

我们再看enumeration类型:

[cpp] view plaincopy
  1. 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:

[cpp] view plaincopy
  1. enum Color { red, white, blue };  
  2.    
  3. void f()  
  4. {  
  5.    int n;  
  6.    n = red;    // change n to 0  
  7.    n = white;  // change n to 1  
  8.    n = blue;   // change n to 2  
  9. }   


以下代码也说明了Color会自动转换成int:

[cpp] view plaincopy
  1. void f()  
  2. {  
  3.    Color x = red;  
  4.    Color y = white;  
  5.    Color z = blue;  
  6.    
  7.    int n;  
  8.    n = x;   // change n to 0  
  9.    n = y;   // change n to 1  
  10.    n = z;   // change n to 2  
  11. }   


但是,C++编译器并不提供从int转换成Color的自动转换:

[cpp] view plaincopy
  1. void f()  
  2. {  
  3.    Color x;  
  4.    x = blue;  // change x to blue  
  5.    x = 2;     // compile-time error: can't convert int to Color  
  6. }   

 

若你真的要从int转换成Color,应提供强制类型转换:

[cpp] view plaincopy
  1. void f()  
  2. {  
  3.    Color x;  
  4.    x = red;      // change x to red  
  5.    x = Color(1); // change x to white  
  6.    x = Color(2); // change x to blue  
  7.    x = 2;        // compile-time error: can't convert int to Color  
  8. }   
0 0
原创粉丝点击