02. Prefer consts, enums, and inlines to #defines

宏定义

#define ASPECT_RATIO 1.653

ASPECT在编译之前已被预编译就行替换,不会进入符号表(symbol table),
如出现1.653导致的编译错误,不方便调试追踪。

可以使用

const double AspectRatio = 1.653

AspectRatio会进入符号表。

类中宏定义

class GamePlayer
{
...
private:
	#define NUM_TURNS 5
	int scores[NUM_TURNS];
};

可以将其定义为static const(const static一样)类型,

class GamePlayer
{
...
private:
	static const int NUM_TURNS = 5; // static const类型的数据成员中只有static const int成员能够进行类内初始化
	int scores[NUM_TURNS];
};

也可以使用enum hack,

class GamePlayer
{
...
private:
	enum { NumTurns = 5 };
	int scores[NumTurns];
	...	
};

宏定义函数

#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
int a = 5, b = 0;
CALL_WITH_MAX(++a, b); // a被累加二次
CALL_WITH_MAX(++a, b+10); // a被累加一次

即使在每个参数都加上小括号,任然会出现边际效用。
调用f之前,a的递增次数取决于"它被拿来和谁比较"!

替代方法:

template<typename T>
inline void CallWithMax(const T&a , const T& b)
{
	f(a > b ? a : b);
}

结论:
使用const是、enums和inlines可以降低对预处理(特别是#define)的需求,但仍有使用它的需求: 包含头文件之#include、条件编译#ifdef/#ifndef。

请记住:

  • 对于单纯常量,最好以const对象或enums替换#defines。
  • 对于形似函数的宏,最好以inline函数替换#defines。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值