“宁可以编译器替换预处理器”
1.对于单独常量,最好以const对象或者enums替换#defines
即:不要使用
#define ASPECT_RATIO 1.653
原因:所使用的名称可能并未进入记号表(symbol table)
而要使用
const double AspectRatio = 1.653
以常量替换#defines,有两重特殊情况:
1.定义常量指针:
定义一个常量char*-based字符串,须使用const两次:
const char * const authorName = “Scott Meyers”
当然,这样定义更好
const std::string authorName (“Scott Meyers”)
class GamePlayer{
private:
static const int NumTurns = 5; //常量声明式
int scores[NumTurns];//使用该常量
};
const int GamePlayer::NumTurns; //定义
为了让常量的作用域限制于class内,必须使其成为class的一个成员(member);
为确保常量至多只有一份实体,必须为static成员。
2. 对于形似函数的宏(macro),最好改用inline函数替换#define
不要用
//以a和b的较大值调用f
#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 inline函数(30)
template<typenameT>
inline void callWithMax( const T &a, const T &b )
{
f(a > b ? a : b);
}