匿名枚举的使用

2021-12-29 00:00:00 enums c++

匿名enum声明的目的是什么,例如:

What is the purpose of anonymous enum declarations such as:

enum { color = 1 };

为什么不直接声明int color = 1?

推荐答案

枚举不占用任何空间并且是不可变的.

Enums don't take up any space and are immutable.

如果您使用 const int color = 1; 那么您将解决可变性问题,但如果有人获取了 color (const int* p =&color;) 然后必须为其分配空间.这可能不是什么大问题,但除非您明确希望人们能够获取color的地址,否则您最好阻止它.

If you used const int color = 1; then you would solve the mutability issue but if someone took the address of color (const int* p = &color;) then space for it would have to be allocated. This may not be a big deal but unless you explicitly want people to be able to take the address of color you might as well prevent it.

此外,在类中声明常量字段时,它必须是 static const (对于现代 C++ 不适用) 并且并非所有编译器都支持静态的内联初始化const 成员.

Also when declaring a constant field in a class then it will have to be static const (not true for modern C++) and not all compilers support inline initialization of static const members.

免责声明:不应将此答案视为对所有数字常量使用 enum 的建议.你应该做你(或你的同事)认为更具可读性的事情.答案只是列出了一些可能更喜欢使用 enum 的原因.

Disclaimer: This answer should not be taken as advice to use enum for all numeric constants. You should do what you (or your co-workers) think is more readable. The answer just lists some reasons one might prefer to use an enum.

相关文章