Enum.1: Prefer enumerations over macros
Enum.1: 枚舉類型比宏定義好
Reason(原因)
Macros do not obey scope and type rules. Also, macro names are removed during preprocessing and so usually don't appear in tools like debuggers.
宏定義不需要遵守範圍和類型規則。同時,宏定義名稱會在預編譯極端被替換因此通常也不會出現在調試器等工具中。
Example(示例)
First some bad old code:
首先是一些不好的老式代碼:
<code>// webcolors.h (third party header)
#define RED 0xFF0000
#define GREEN 0x00FF00
#define BLUE 0x0000FF
// productinfo.h
// The following define product subtypes based on color
#define RED 0
#define PURPLE 1
#define BLUE 2
int webby = BLUE; // webby == 2; probably not what was desired/<code>
Instead use an enum:
使用枚舉替代:
<code>enum class Web_color { red = 0xFF0000, green = 0x00FF00, blue = 0x0000FF };
enum class Product_info { red = 0, purple = 1, blue = 2 };
int webby = blue; // error: be specific
Web_color webby = Web_color::blue;/<code>
We used an enum class to avoid name clashes.
我們可以使用枚舉類來避免名稱衝突。
Enforcement(實施建議)
Flag macros that define integer values.
標記整數類型的宏定義。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum1-prefer-enumerations-over-macros
覺得本文有幫助?請分享給更多人。
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章