C++核心准则Enum.1: 枚举类型比宏定义好
面向对象思考
共 1163字,需浏览 3分钟
·
2020-03-11 23:25
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
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!
评论