Enum.2: Use enumerations to represent sets of related named constants
Enum.2: 使用枚舉表現一組相關的命名常量
Reason(原因)
An enumeration shows the enumerators to be related and can be a named type.
枚舉類型表示枚舉值之間具有相關性,並且可以成為命名類型。
Example(示例)
<code>enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };/<code>
Note(注意)
Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
啟用枚舉類型屬於常規操作,並且編譯器可以對不平常的用法進行警示。例如:
<code>enum class Product_info { red = 0, purple = 1, blue = 2 };
void print(Product_info inf)
{
switch (inf) {
case Product_info::red: cout << "red"; break;
case Product_info::purple: cout << "purple"; break;
}
}/<code>
Such off-by-one switch-statements are often the results of an added enumerator and insufficient testing.
這種"只越界一點"的switch語句通常是增加枚舉值後沒有充分測試的結果。
Enforcement(實施建議)
- Flag switch-statements where the cases cover most but not all enumerators of an enumeration.
- 提示switch語句覆蓋大多數枚舉值卻沒有覆蓋所有枚舉值的情況。
- Flag switch-statements where the cases cover a few enumerators of an enumeration, but has no default.
- 提示swtich語句覆蓋了少數枚舉值卻沒有default分支的情況。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum2-use-enumerations-to-represent-sets-of-related-named-constants
覺得本文有幫助?請分享給更多人。
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章