C++核心準(zhǔn)則Enum.3:枚舉類?要比普通的枚舉類型好

Enum.3: Prefer class enums over "plain" enums
Enum.3:枚舉類要比普通的枚舉類型好
Reason(原因)
To minimize surprises: traditional enums convert to int too readily.
盡量減少意外性:經(jīng)典的枚舉類型太容易轉(zhuǎn)換為整數(shù)了。
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:
而使用枚舉類的時(shí)候:
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.
(簡(jiǎn)單)警告所有枚舉類以外的枚舉定義。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum3-prefer-class-enums-over-plain-enums
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評(píng)論
圖片
表情
