面试题答案
一键面试传统枚举类型和强类型枚举(enum class)在类型安全方面的不同
- 传统枚举类型:
- 传统枚举类型属于弱类型,其枚举值可以隐式转换为整数类型,不同枚举类型之间如果底层类型相同也可能发生混淆。
- 例如:
enum Color {
RED,
GREEN,
BLUE
};
enum Size {
SMALL,
MEDIUM,
LARGE
};
void func(int num) {
// 函数期望一个整数参数
std::cout << "Received num: " << num << std::endl;
}
int main() {
Color c = RED;
Size s = SMALL;
func(c); // 可以编译通过,因为Color类型可以隐式转换为int,这可能导致类型混淆
func(s); // 同样可以编译通过,Size类型也隐式转换为int,混淆了不同的枚举语义
return 0;
}
- 强类型枚举(enum class):
- 强类型枚举(enum class)是强类型的,枚举值不会隐式转换为其他类型,不同的enum class类型即使底层类型相同也不能相互混淆。
- 例如:
enum class Color {
RED,
GREEN,
BLUE
};
enum class Size {
SMALL,
MEDIUM,
LARGE
};
void func(int num) {
// 函数期望一个整数参数
std::cout << "Received num: " << num << std::endl;
}
int main() {
Color c = Color::RED;
Size s = Size::SMALL;
// func(c); // 编译错误,Color类型不能隐式转换为int
// func(s); // 编译错误,Size类型不能隐式转换为int
return 0;
}
利用枚举类型的类型安全特性避免常见错误
- 使用强类型枚举避免类型混淆:
- 例如,假设有一个函数根据颜色来执行不同的操作:
enum class Color {
RED,
GREEN,
BLUE
};
void performAction(Color color) {
switch (color) {
case Color::RED:
std::cout << "Performing action for red." << std::endl;
break;
case Color::GREEN:
std::cout << "Performing action for green." << std::endl;
break;
case Color::BLUE:
std::cout << "Performing action for blue." << std::endl;
break;
}
}
int main() {
Color c = Color::GREEN;
performAction(c);
// performAction(1); // 编译错误,避免了传入错误类型(如整数1)导致的逻辑错误
return 0;
}
- 显式转换:
- 如果确实需要将强类型枚举转换为整数,可以进行显式转换:
enum class Color {
RED,
GREEN,
BLUE
};
void performAction(int num) {
std::cout << "Received num: " << num << std::endl;
}
int main() {
Color c = Color::RED;
performAction(static_cast<int>(c)); // 显式转换为int
return 0;
}
这样通过显式转换,清晰地表明了类型转换的意图,提高了代码的可读性和安全性。