enum是枚举类型就不多说了,用于自定义的数据。
现在说下enum和enum class有什么区别,为什么要用enum class。
enum有几种限制:
1.两个enum不能定义同样名称的数据,如下,会报重复定义的编译错误
// Defining enum1 Gender
enum Gender { Male,
Female };
// Defining enum2 Gender2 with same values
// This will throw error
enum Gender2 { Male,
Female };
2.如果一个名称在enum里,就不能再定义这个名称的变量,如下,会报重定义的编译错误。
// Defining enum1 Gender
enum Gender { Male,
Female };
// Creating Gender type variable
Gender gender = Male;
// creating a variable Male
// this will throw error
int Male = 10;
3.enum是类型不安全的
// Defining enum1 Gender
enum Gender { Male,
Female };
// Defining enum2 Color
enum Color { Red,
Green };
// Creating Gender type variable
Gender gender = Male;
Color color = Red;
// Upon comparing gender and color
// it will return true as both have value 0
// which should not be the case actually
if (gender == color)
cout << "Equal";
猜猜这两个enum会相等吗?
答案是会的,会输出"Equal",这明明是两个不同的enum,但是enum里面的默认值是一样的。
但编译器会报warning信息
warning: comparison between ‘enum main()::Gender’ and ‘enum main()::Color’
所以需要enum class,它有以下特点
使用时像下面这样
// Declaration
enum class EnumName{ Value1, Value2};
// Initialisation
EnumName ObjectName = EnumName::Value1;
enum class会克服enum的上面列举的限制
int main()
{
//相同的名称可以出现在不同的enum class中
enum class Color { Red,
Green,
Blue };
enum class Color2 { Red,
Black,
White };
enum class People { Good,
Bad };
// 可以定义变量名和enum class里的相同
int Green = 10;
// Instantiating the Enum Class
Color x = Color::Green;
// Comparison now is completely type-safe
if (x == Color::Red)
cout << "It's Red\n";
else
cout << "It's not Red\n";
People p = People::Good;
if (p == People::Bad)
cout << "Bad people\n";
else
cout << "Good people\n";
// gives an error
// if(x == p)
// cout<<"red is equal to good";
// won't work as there is no
// implicit conversion to int
// cout<< x;
cout << int(x);
return 0;
}