switch case 不能用enum
时间: 2024-05-29 07:07:12 浏览: 115
switch case语句可以用于整型、字符型等基本类型的变量,但是不能用于枚举类型,这是由于枚举类型在C/C++中本质上是整型。因此,在使用switch case语句时,应该使用整型变量或者字符型变量作为条件表达式。如果需要使用枚举类型作为条件表达式,可以使用if else语句来代替switch case语句。
举个例子,如果有如下的枚举类型:
```
enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday };
```
那么,下面的代码是错误的:
```
Weekday day = Monday;
switch (day) {
case Monday:
cout << "Today is Monday" << endl;
break;
case Tuesday:
cout << "Today is Tuesday" << endl;
break;
...
}
```
应该改为如下的代码:
```
Weekday day = Monday;
int iDay = static_cast<int>(day);
switch (iDay) {
case 0:
cout << "Today is Monday" << endl;
break;
case 1:
cout << "Today is Tuesday" << endl;
break;
...
}
```
阅读全文