编译器vs预处理器
- define为预处理器命令。
- 所以应该尽量少用预处理器命令。
define带来的问题
#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653;
-
符号表问题
- 问题:编译器看不见define的名字。所以报告错误让人困惑。define的名字,没有进入symbol
table - 解决:使用const代替define
- 问题:编译器看不见define的名字。所以报告错误让人困惑。define的名字,没有进入symbol
-
多份问题。
预处理器盲目替换,可能导致多分define变量拷贝。const则不存在只会有一份副本。
char pointer based vs string
const char * const authorName = "Scott Meyers";
const std::string authorName("Scott Meyers"); // 比const char *const 更好
class 的成员
class GamePlayer {
private:
static const int NumTurns = 5; // 确保一个类只有一个副本,那么只能为static。这是一个声明不是定义。新编译器支持这样的语法,在声明的时候赋初值。
int scores[NumTurns];
};
const int GamePlayer::NumTurns; // 这是定义式
可能旧的编译器是不支持这样的。
class CostEstimate {
private:
static const double FudgeFactor; // 生命
};
// 在另外的文件中定义
const double CostEstimate::FudgeFactor = 1.35;
enum hack
注意我们还是可以取地址访问到FudgeFactor.如何隐藏它呢?
class GamePlayer {
private:
enum { NumTurns = 5 };
int scores[NumTurns];
};
define and inline
// call f with the maximum of a and b
#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))
注意使用define的话,全部要用小括号包起来。即便如此也会有问题
inta=5,b=0;
CALL_WITH_MAX(++a, b); // a is incremented twice
CALL_WITH_MAX(++a, b+10); // a is incremented once
inline 函数的好处
template<typename T>
inline void callWithMax(const T& a, const T& b) {
f(a>b?a:b);
}
inline是正真的函数,有参数检查。