共用方式為


Conversions and Enumerated Types 

Because enumerated types are integral types, any enumerator can be converted to another integral type by integral promotion. Consider this example:

// enumerated_types.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

enum Days
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

int  i;
Days d = Thursday;
int main()
{
   i = d;    // Converted by integral promotion.
   cout << "i = " << i << "\n";
}

Output

i = 4

However, there is no implicit conversion from any integral type to an enumerated type. Therefore (continuing with the preceding example), the following statement is in error:

d = 6;    // Erroneous attempt to set d to Saturday.

Assignments such as this, where no implicit conversion exists, must use a cast to perform the conversion:

d = (Days)6;    // Explicit cast-style conversion to type Days.
d = Days( 4 );  // Explicit function-style conversion to type Days.

The preceding example shows conversions of values that coincide with the enumerators. There is no mechanism that protects you from converting a value that does not coincide with one of the enumerators. For example:

d = Days( 967 );

Some such conversions may work. However, there is no guarantee that the resultant value will be one of the enumerators. Additionally, if the size of the enumerator is too small to hold the value being converted, the value stored may not be what you expect.

See Also

Reference

C++ Enumeration Declarations