effective C++ 条款 2:尽量用const和inline而不用#define

effective C++ 条款 2:尽量用const和inline而不用#define

尽量用编译器而不用预处理

#define ASPECT_RATIO 1.653 它会被预处理程序去掉,于是ASPECT_RATIO不会加入到符号列表中

定义指针常量时会有点不同 要写两次const:const char * const authorName = "Scott Meyers";

最好用const std::string authorName("Scott Meyers");

另外,定义某个类(class)的常量一般也很方便 而define没有作用域。

要把常量限制在类中,首
先要使它成为类的成员;为了保证常量最多只有一份拷贝,还要把它定义为静态成员:
     
class GamePlayer {
private:
 static const int NUM_TURNS = 5; // constant declaration  

//如果编译器不支持in class 初值设定,可改用 “the enum hack”

// enum {NumTurn = 5};
 int scores[NUM_TURNS];  // use of constant
 ...
};
 
还有一点,正如你看到的,上面的语句是NUM_TURNS的声明,而不是定义,所以你还必
须在类的实现代码文件中定义类的静态成员:  
const int GamePlayer::NUM_TURNS; // mandatory definition;
  // goes in class impl.file 

旧一点的编译器会不接受这种语法,因为它认为类的静态成员在声明时定义初始值是非法
的;而且,类内只允许初始化整数类型(如:int, bool, char 等),还只能是常量。
在上面的语法不能使用的情况下,可以在定义时赋初值:
class EngineeringConstants { // this goes in the class
private:  // header file
 static const double FUDGE_FACTOR;
 ...
};
 // this goes in the class implementation file
 const double EngineeringConstants::FUDGE_FACTOR = 1.35;

(编译过程中编译器一定要知道数组的大小)

为了弥补那些(不正确地)禁止类内进行整型类常量初始化的编译器的不足,可以采用
称之为“借用enum”的方法来解决。这种技术很好地利用了当需要int类型时可以使用枚举类
型的原则,所以GamePlayer也可以象这样来定义:

class GamePlayer {
private:
 enum { NUM_TURNS = 5 } // "the enum hack" — makes
 // NUM_TURNS a symbolic name  
 // for 5
 int scores[NUM_TURNS];// fine
};
#define max(a,b) ((a) > (b) ? (a) : (b))

int a = 5, b = 0;
max(++a, b);// a 的值增加了 2 次

max(++a, b+10); // a 的值只增加了 1次

template<class T>
inline const T& max(const T& a, const T& b)
{ return a > b ? a : b; }

原文地址:https://www.cnblogs.com/lidan/p/2239476.html