effective C++学习笔记(01)

条款(1):尽量使用const和inline而不使用#define

1.1为什么不使用#define

每一年IT应届生找工作时候,最常见的一类笔试题就是如下:

写出下面的程序的输出结果

 

#define foo(a,b) (a*b)
//... ...
int main() {
cout
<<foo(1+2,3+4)<<endl;
}

原本些这段程序的人期望的结果是:3*7=21,实际的结果却是1+2*3+4=11。

这就是#define所带来的错误

 

也许你可以提出一下的改进方法,比如

 

#include <iostream>
#define max(a,b) ((a)>(b)?(a):(b))
using namespace std;

int main()
{
cout
<<max(1+2,2+4);
return 0;
}

这样就解决上面出现的问题,程序按照期望输出了6。

 

但是在如下这种情况下还是会出现不期望的错误:

 

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

因此书上建议的是:

 

1.将max换成内联函数

 

inline int max(int a, int b) { return a > b ? a : b; }

为了增加这个函数的实用面,可以利用函数模版

 

 

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

2.将

#define ASPECT_RATIO 1.653

换成

 

 

const double ASPECT_RATIO = 1.653;

3.在定义与类相关的常量时一定要加上static关键字

 

 

class GamePlayer {
private:
static const int NUM_TURNS = 5; // constant eclaration
int scores[NUM_TURNS]; // use of constant
...
};

 

 

 

#include <iostream>
#define foo(a,b) (a*b)
using namespace std;
//... ...
int main() {
    cout<<foo(1+2,3+4)<<endl;
}
posted @ 2010-10-24 22:31  mongg  阅读(202)  评论(0编辑  收藏  举报