C++核心准则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.

宏定义不需要遵守范围和类型规则。同时,宏定义名称会在预编译极端被替换因此通常也不会出现在调试器等工具中。

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(实施建议)

Flag macros that define integer values.

标记整数类型的宏定义。

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum1-prefer-enumerations-over-macros


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

原创文章 414 获赞 724 访问量 35万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/105937058