C++核心准则Enum.2: 使用枚举表现一组相关的命名常量

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源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索