C++核心準則Enum.2: 使用枚舉表現(xiàn)一組相關(guān)的命名常量

Enum.2: Use enumerations to represent sets of related named constants
Enum.2: 使用枚舉表現(xiàn)一組相關(guān)的命名常量
Reason(原因)
An enumeration shows the enumerators to be related and can be a named type.
枚舉類型表示枚舉值之間具有相關(guān)性,并且可以成為命名類型。
Example(示例)
enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };Note(注意)
Switching on an enumeration is common and the compiler can warn against unusual patterns of case labels. For example:
啟用枚舉類型屬于常規(guī)操作,并且編譯器可以對不平常的用法進行警示。例如:
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;
}
}
Such off-by-one?switch-statements are often the results of an added enumerator and insufficient testing.
這種"只越界一點"的switch語句通常是增加枚舉值后沒有充分測試的結(jié)果。
Enforcement(實施建議)
Flag?switch-statements where the?cases cover most but not all enumerators of an enumeration.
提示switch語句覆蓋大多數(shù)枚舉值卻沒有覆蓋所有枚舉值的情況。
Flag?switch-statements where the?cases cover a few enumerators of an enumeration, but has no?default.
提示swtich語句覆蓋了少數(shù)枚舉值卻沒有default分支的情況。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum2-use-enumerations-to-represent-sets-of-related-named-constants
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
