https://blog.csdn.net/lihao21/article/details/6825722
How to correctly understand enum types?
E.g:
- enum Color { red, white, blue};
- 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:
- 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:
- 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
- }
The following code also shows that Color is automatically converted to 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
- }
However, the C++ compiler does not provide automatic conversion from int to Color:
- void f()
- {
- Color x;
- x = blue; // change x to blue
- x = 2; // compile-time error: can't convert int to Color
- }
If you really want to convert from int to Color, provide a cast:
- 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
- }
But you should ensure that the Color type converted from int makes sense.
Reference link: Click to open the link