C++编程思想读书笔记-9 内联函数

1 在C语言中使用宏可以提高程序效率,但宏容易出错

在宏定义中,最好给变量打上括号,否则容易出错.

于处理器 无法对宏的参数类型和返回值进行简单

宏和普通函数是有区别的,普通函数是值传递或者地址传递,但宏是简单地拷贝,特别参数是a++这种容易使a++多次执行


2 在宏里,没法表示类的作用范围.所以类中不能使用宏.转而使用内联函数

在类的声明中直接写上函数定义的默认是inline函数

内联函数和普通函数差不多,会受到编译器的检查参数列表和返回值. 但在调用时可以直接将函数直接替换成函数体,减小调用开销,

但是否内联是编译器决定的,即使明确写上inline也可能不按内联进行替换,下面两种情况是明确不能内联的:

1 函数体复杂,比如有循环就不能内联,原因是复杂的函数体替换会削弱甚至不会带来性能上的提高

2 显示或隐式地取该函数地址,编译器必须为函数体分配内存


3 向前引用

 

	class F
	{
		public:
			int f() const { return g()+1; }
			int g() const {return 1;} 
	}


C++规定: 只有在类声明结束后,类中的内联函数才起作用

 

所以引用未声明的内部函数是可以的


4 内联无法取代宏的地方:

字符串定义: 将任意标识符转换成字符串数组

 

 

#define F(s) cout<< #s << endl; s ;

 

 

标志粘贴:

 

 

#define D1(x) int x##one; 
#define D2(x) int x##two; 

 

 


head.h

 

#ifndef HEAD_H
#define HEAD_H

#define F(s) cout<< #s << endl; s ;
#define D1(x) int x##one; 
#define D2(x) int x##two;

class Forward
{
        public:
                int f() {return g() +1;}
                int g() {return 1;}

};


#endif


 

main.cpp

 

#include <string>
#include <iostream>

#include "head.h"

using namespace std;

int main()
{
        F(cout << "abc" << endl;);
        D1(num);
        D2(num);
        numone = 100;
        numtwo = 200;


        F(cout<<numone << ' ' << numtwo << endl;);


        Forward f1;
        cout << f1.f() << endl;
        cout << f1.g() << endl;
}


zhao@ubuntu:~/c++work/cpp9$ ./a.out 
cout << "abc" << endl;
abc
cout<<numone << ' ' << numtwo << endl;
100 200
2
1


 


 

posted @ 2013-06-10 20:20  jlins  阅读(238)  评论(0编辑  收藏  举报