定义枚举方法(使用枚举类定义枚举类型)
定义枚举方法(使用枚举类定义枚举类型)(Simple) Warn on any non-class enum definition.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.Enforcemen
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
觉得本文有帮助?请分享给更多人。
更多精彩文章欢迎关注微信公众号【面向对象思考】!
面向对象开发,面向对象思考!