“寧可以編譯器替換預處理器”
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);
}