在实际使用 C++ 的过程中,经常需要使用到枚举,然而在 C++ 中并不能给枚举添加方法,属性等特性,如果要使用这些特性,需要通过一些特殊的办法来做到,对枚举进行一个封装。

以当前用到的封装移动方式为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class URMoveState {
public:
enum StateEnum {
MOVEC = 0,
MOVEJ = 1,
MOVEL = 2,
MOVEP = 3
};
StateEnum _state;

explicit URMoveState(const StateEnum &state) : _state(state) {};

// 重载等于
inline bool operator==(const URMoveState &rhs) {
return _state == rhs._state;
}
inline bool operator==(const StateEnum &rhs) {
return _state == rhs;
}

// 重载不等于
inline bool operator!=(const URMoveState &rhs) {
return _state != rhs._state;
}
inline bool operator!=(const StateEnum &rhs) {
return _state != rhs;
}

std::string name() {
switch (_state) {
case MOVEC:return "movec";
case MOVEJ:return "movej";
case MOVEL:return "movel";
case MOVEP:return "movep";
}
}
// and so on ...
};

评论