C++核心準(zhǔn)則Enum.1: 枚舉類型比宏定義好

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.
宏定義不需要遵守范圍和類型規(guī)則。同時,宏定義名稱會在預(yù)編譯極端被替換因此通常也不會出現(xiàn)在調(diào)試器等工具中。
Example(示例)
First some bad old 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
Instead use an?enum:
使用枚舉替代:
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;
We used an?enum class?to avoid name clashes.
我們可以使用枚舉類來避免名稱沖突。
Enforcement(實(shí)施建議)
Flag macros that define integer values.
標(biāo)記整數(shù)類型的宏定義。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum1-prefer-enumerations-over-macros
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
評論
圖片
表情
