C++核心准则Enum.3:枚举类要比普通的枚举类型好
面向对象思考
共 1124字,需浏览 3分钟
·
2020-03-13 23:23
Enum.3: Prefer class enums over "plain" enums
Enum.3:枚举类要比普通的枚举类型好
Reason(原因)
To minimize surprises: traditional enums convert to int too readily.
尽量减少意外性:经典的枚举类型太容易转换为整数了。
Example(示例)
void Print_color(int color);
enum Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum Product_info { red = 0, purple = 1, blue = 2 };
Web_color webby = Web_color::blue;
// Clearly at least one of these calls is buggy.
Print_color(webby);
Print_color(Product_info::blue);
Instead use an enum class:
而使用枚举类的时候:
void Print_color(int color);
enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum class Product_info { red = 0, purple = 1, blue = 2 };
Web_color webby = Web_color::blue;
Print_color(webby); // Error: cannot convert Web_color to int.
Print_color(Product_info::red); // Error: cannot convert Product_info to int.
Enforcement(示例)
(Simple) Warn on any non-class enum definition.
(简单)警告所有枚举类以外的枚举定义。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum3-prefer-class-enums-over-plain-enums
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论