Enum.2: Use enumerations to represent sets of related named constants
Enum.2: 使用枚舉表現一組相關的命名常量
git
Reason(緣由)
An enumeration shows the enumerators to be related and can be a named type.github
枚舉類型表示枚舉值之間具備相關性,而且能夠成爲命名類型。
web
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:app
啓用枚舉類型屬於常規操做,而且編譯器能夠對不日常的用法進行警示。例如:ide
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語句一般是增長枚舉值後沒有充分測試的結果。
測試
Enforcement(實施建議)ui
Flag switch-statements where the cases cover most but not all enumerators of an enumeration.spa
提示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
以爲本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
本文分享自微信公衆號 - 面向對象思考(OOThinkingDalian)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。