枚举类enum class
C++的枚举类(enum class)是一个在C++11引入的重要特性,用于替代传统的枚举,主要是为了让枚举类型更加安全、明确、可控
语法
1
2
3
4
5
| enum class Color {
Red,
Green,
Blue
};
|
与传统枚举对比
特性 | 传统 enum | enum class(强类型枚举) |
---|
命名作用域 | 枚举成员暴露到外层作用域 | 枚举成员限定在枚举作用域内 |
类型安全 | 可隐式转换为 int | 不能隐式转换为 int |
允许同名枚举值 | 不允许(会冲突) | 允许不同枚举类中出现相同名字 |
底层类型 | 实现定义(通常是 int ) | 可显式指定底层类型 |
推荐程度 | 旧式写法,已不推荐 | ✅ 推荐使用 |
1
2
3
4
| enum Color { Red, Green, Blue};
enum Fruit { Apple, Banana, Red }; // ❌ 错误:Red重定义
int c = Red; // ✔ 可自动转为int
|
1
2
3
4
5
| enum class Color { Red, Green, Blue };
enum class Fruit { Red, Banana, Apple }; // ✔ 不冲突
int c = Color::Red; // ❌ 错误,不能隐式转int
int n = static_cast<int>(Color::Red); // ✔ 显示转换
|
指定底层类型
枚举类可以显式指定底层存储类型,节省空间或与外部接口兼容
1
2
3
4
5
| enum class Status : unsigned char {
ok = 0,
Error = 1,
Unknown = 255
};
|
指定枚举值
1
2
3
4
5
6
| enum class Direction {
North = 1,
East = 2,
South = 4,
West = 8
};
|
常见用法
1
2
3
4
5
6
7
8
9
10
11
12
| #include <iostream>
#include <array>
using namespace std;
enum class Color {Red, Green, Blue};
int main() {
array<Color, 3> colors = {Color::Red, Color::Green, Color::Blue};
for (auto c:colors) {
cout << static_cast<int>(c) << endl;
}
}
|
总结
比较项 | 传统 enum | enum class |
---|
是否强类型 | 否 | ✅ 是 |
是否作用域隔离 | 否 | ✅ 是 |
是否允许隐式转int | ✅ 是 | ❌ 否 |
是否推荐使用 | ❌ 否 | ✅ 是(C++11起) |
类中的枚举类型
传统
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| #include <iostream>
using namespace std;
class Task {
public:
enum Status {
Pending,
Running,
Finished
};
Status state;
Task() : state(Pending) {}
};
int main() {
Task t;
t.state = Task::Running; // ✅ 必须加类名限定符
cout << t.state << endl; // 输出 1(枚举转int)
}
|
- 定义在类作用域内
- 访问时需要
类名::枚举名
- 枚举成员仍可以隐式转换为int
- 与类的命名空间绑定,不会与外部冲突
现代用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| #include <iostream>
using namespace std;
class Task {
public:
enum class Status {
Pending,
Running,
Finished
};
Status state;
Task() : state(Status::Pending) {}
};
int main() {
Task t;
t.state = Task::Status::Running; // ✅ 强作用域
cout << static_cast<int>(t.state) << endl;
}
|
- 强类型安全,不会隐式转换为
int
- 作用域限定,访问时需
Task::Status::Running
可以自定义底层类型
1
| enum class Status : uint8_t { Pending, Running, Finished };
|