本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
尽量以const, enum,inline 替换 #define --》 宁可以编译器替换预处理器
1.对于单纯常量,最好以const 对象或enum替换#define
不要用
#define ASPECT_RATIO 1.653
而用
const double AspectRatio = 1.653
两点注意
1.指向常量char *的字符串的常量指针
const char * const authorName = “Scott Meyers”
第一个const 表示指针指向的内容是不变的;第二个const表示指针本身的值是不变的
2.class专属常量
#include <iostream>
using namespacestd;
class A{
private:
static const int num = 5; //声明
int score[num];
};
const intA::num; //定义
int main(){
//constint A::num; //error: member A::num cannot be define in the current scope
system("pause");
}
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被累加一次
而用
template<typenameT>
inline void callWithMax(const T &a, const T &b)
//由于不知道T是什么类型,所以采用pass by reference-to-const
{
f(a > b ? a : b);
}