The usage of anonymous enums(匿名枚举的使用)
问题描述
匿名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.
这篇关于匿名枚举的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:匿名枚举的使用
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
