1、宏定义一个常量:
#define ASPECT_RATIO 1.653
替换为const修饰常量:
const double AspectRatio=1.653;
2、常量指针:
const char *authorName = "Scott Meyers";
替换为
const std::string authorName("Scott Meyers");
3、class专属常量,常量的作用域限制于class内,确保常量只有一个,必须声明为static成员;
class专属常量声明式:
//头文件内
class GamePlayer{
private:
static const int NumTurns = 5;
int scores[NumTurns];
...
};
定义式如下,放在实现文件(由于声明NumTurns时设初值5,因此不可以再设初值);
//cpp文件内
const int GamePlayer::NumTurns;
旧编译器不支持上述语法,可以按如下方式声明和定义:
//头文件内
class CostEstimate{
private:
static const double FudgeFactor;
...
};
//cpp文件内
const double CostEstimate::FudgeFactor = 1.35;
如果数组声明式中,编译器必须在编译期间知道数组的大小,可改用the enum hack补偿做法,可定义如下:
class GamePlayer{
private:
enum { NumTurns = 5};
int scores[NumTurns];
...
}
4、函数调用的宏:
//a、b的较大值调用f
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
替换为template inline函数:
template<typename T>
inline void callWithMax(const T& a, const T& b)
{
f(a>b ? a : b);
}
笔记:
1.对于单纯常量,最好以const对象或enum替换#define;
2.对于形似函数的宏,最好改用inline函数替换#define。