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.
这篇关于匿名枚举的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:匿名枚举的使用
基础教程推荐
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
