文章

C++ enum枚举

C++ enum枚举

枚举类enum class

C++的枚举类(enum class)是一个在C++11引入的重要特性,用于替代传统的枚举,主要是为了让枚举类型更加安全、明确、可控

语法

1
2
3
4
5
enum class Color {
	Red,
	Green,
	Blue
};

与传统枚举对比

特性传统 enumenum 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;
	}
}

总结

比较项传统 enumenum 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 };
      
本文由作者按照 CC BY 4.0 进行授权