面试题答案
一键面试- switch语句参数类型常见选择:
- 整型:包括
int
、short
、long
等有符号整型,以及unsigned int
、unsigned short
、unsigned long
等无符号整型。例如:
int num = 2; switch (num) { case 1: std::cout << "The number is 1" << std::endl; break; case 2: std::cout << "The number is 2" << std::endl; break; default: std::cout << "Other number" << std::endl; }
- 字符型:
char
类型也可以作为switch
语句的参数。例如:
char ch = 'a'; switch (ch) { case 'a': std::cout << "It's a" << std::endl; break; case 'b': std::cout << "It's b" << std::endl; break; default: std::cout << "Other character" << std::endl; }
- 枚举类型:用户自定义的枚举类型也能作为
switch
语句的参数,下面会详细说明注意事项及举例。
- 整型:包括
- 使用枚举类型作为switch参数的注意事项及举例:
- 注意事项:
- 枚举值必须是唯一的,在
switch
语句中不能有重复的case
值。 - 枚举类型的底层类型默认是
int
,如果显式指定了底层类型,switch
语句会按照指定的底层类型来处理。
- 枚举值必须是唯一的,在
- 举例:
这里定义了一个enum class Color { RED, GREEN, BLUE }; Color color = Color::GREEN; switch (color) { case Color::RED: std::cout << "The color is red" << std::endl; break; case Color::GREEN: std::cout << "The color is green" << std::endl; break; case Color::BLUE: std::cout << "The color is blue" << std::endl; break; default: std::cout << "Other color" << std::endl; }
enum class
(强类型枚举),在switch
语句中使用时,case
标签必须使用枚举值的完整限定名,因为enum class
不会进行隐式类型转换。如果是普通枚举(enum
),在switch
语句中case
标签可以直接使用枚举值,如:enum Color2 { RED2, GREEN2, BLUE2 }; Color2 color2 = GREEN2; switch (color2) { case RED2: std::cout << "The color is red2" << std::endl; break; case GREEN2: std::cout << "The color is green2" << std::endl; break; case BLUE2: std::cout << "The color is blue2" << std::endl; break; default: std::cout << "Other color2" << std::endl; }
- 注意事项: