[Turn] C/C++ experience: mutual conversion between enum and int

https://blog.csdn.net/lihao21/article/details/6825722

 

How to correctly understand enum types?


E.g:

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


We should say that x is of type Color, and should not understand x as an enumeration type, let alone an int type.

 

Let's look at the enumeration type again:

[cpp]  view plain copy  
 
  1. enum Color { red, white, blue};  


(C programmers in particular!)
The best way to understand this type is to think of its values ​​as red, white, and blue, rather than simply as int values.
The C++ compiler provides a conversion from Color to int. The values ​​of red, white and blue above are 0, 1, and 2. However, you should not simply regard blue as 2. blue is of type Color and can be automatically converted to 2, but for the C++ compiler, there is no automatic conversion from int to Color! (C compilation provides this conversion)

For example, the following code shows that Color is automatically converted to int:

[cpp]  view plain copy  
 
  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. }   


The following code also shows that Color is automatically converted to int:

[cpp]  view plain copy  
 
  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. }   


However, the C++ compiler does not provide automatic conversion from int to Color:

[cpp]  view plain copy  
 
  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. }   

 

If you really want to convert from int to Color, provide a cast:

[cpp]  view plain copy  
 
  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. }   


But you should ensure that the Color type converted from int makes sense.
 

Reference link: Click to open the link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324756110&siteId=291194637