匿名枚举的用法 [英] The usage of anonymous enums

查看:186
本文介绍了匿名枚举的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

匿名枚举的目的是什么?例如:

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 ,并不是所有的编译器都支持inline初始化静态const成员。

Also when declaring a constant field in a class then it will have to be static const and not all compilers support inline initialization of static const members.

免责声明:此回答不应被视为建议对所有数字常量使用 enum 。你应该做你(或你的牛科)认为更可读。答案只列出了一个可能更喜欢使用枚举的原因。

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

这篇关于匿名枚举的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆