首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C++核心准则Enum.8:只在必要时指定枚举值

Enum.8: Specify enumerator values only when necessary

Enum.8: 只在必要时指定枚举值

Reason(原因)

It's the simplest. It avoids duplicate enumerator values. The default gives a consecutive set of values that is good for switch-statement implementations.

这样最简单。可以避免重复的枚举值。默认的情况会分配一组容易被switch语句使用的连续值。

Example(示例)

代码语言:javascript
复制
enum class Col1 { red, yellow, blue };
enum class Col2 { red = 1, yellow = 2, blue = 2 }; // typo
enum class Month { jan = 1, feb, mar, apr, may, jun,
                   jul, august, sep, oct, nov, dec }; // starting with 1 is conventional
enum class Base_flag { dec = 1, oct = dec << 1, hex = dec << 2 }; // set of bits

Specifying values is necessary to match conventional values (e.g., Month) and where consecutive values are undesirable (e.g., to get separate bits as in Base_flag).

为了符合日常习惯(例如月)或者不希望连续值(例如用于获取标志变量中的特定标志位)时有必要定义枚举值。

Enforcement(实施建议)

  • Flag duplicate enumerator values
  • 标记重复的枚举值
  • Flag explicitly specified all-consecutive enumerator values
  • 标记显式定义所有枚举值为连续值情况。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum8-specify-enumerator-values-only-when-necessary


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

举报
领券