前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则Enum.1: 枚举类型比宏定义好

C++核心准则Enum.1: 枚举类型比宏定义好

作者头像
面向对象思考
发布2020-03-25 17:02:04
1.2K0
发布2020-03-25 17:02:04
举报
文章被收录于专栏:C++核心准则原文翻译

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:

首先是一些不好的老式代码:

代码语言:javascript
复制
// 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:

使用枚举替代:

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-03-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档