在C++11及其后续版本中,引入了一个新的枚举类型称为“强类型枚举”或“枚举类”(enumeration class),通常简称为“枚举类”(enum class)。
相对于传统的枚举类型,枚举类有以下特点和优点:
- 强类型:枚举类的成员值不可以隐式转换为整数,也不能与整数值进行比较,除非显式地进行类型转换。
- 作用域:枚举类的成员值是限制在其枚举类作用域内的,所以不同的枚举类中可以有相同名称的成员。
- 明确指定底层类型:可以指定存储枚举成员的底层数据类型。
下面是一个enum class
的例子:
enum class Color {
Red,
Green,
Blue
};
enum class TrafficLight {
Red,
Yellow,
Green
};
int main() {
Color col = Color::Red;
TrafficLight light = TrafficLight::Red;
// 下面的代码是错误的,因为枚举类成员不能直接与整数比较
// if(col == 0) {...}
// 下面的代码也是错误的,因为不同的枚举类成员不能直接进行比较
// if(col == light) {...}
// 若要与整数比较,需要进行类型转换
if(static_cast<int>(col) == 0) {
// ...
}
return 0;
}
如果你想指定枚举类的底层类型,可以如下操作:
enum class Color : char {
Red,
Green,
Blue
};
在上面的代码中,Color
的底层类型被指定为char
。
枚举类(enum class
)可以被用在switch
语句中。使用枚举类在switch
语句中有个好处:它使得代码更具可读性,因为你必须明确引用枚举的名称。不过,与传统的enum
一样,如果你没有为switch
语句处理所有的枚举值,编译器可能会给出警告(取决于编译器设置和所使用的编译器)。
以下是一个例子来展示如何在switch
语句中使用enum class
:
#include <iostream>
enum class Color {
Red,
Green,
Blue
};
void printColorDescription(Color color) {
switch (color) {
case Color::Red:
std::cout << "Red is the color of fire and blood." << std::endl;
break;
case Color::Green:
std::cout << "Green is the color of nature and life." << std::endl;
break;
case Color::Blue:
std::cout << "Blue is the color of sky and sea." << std::endl;
break;
// 默认情况可以根据需要添加,但在此例中可能不是必需的
// default:
// std::cout << "Unknown color." << std::endl;
}
}
int main() {
Color col = Color::Green;
printColorDescription(col);
return 0;
}
在上述代码中,我们定义了一个enum class
Color
,并在printColorDescription
函数中使用switch
语句来处理其不同的值。