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(示例)
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
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】