内联函数(inline function与一般的函数不同,不是在调用时发生控制转移,而是在编译阶段将函数体嵌入到每一个调用语句中。
内联函数(inline function)与编译器的工作息息相关。编译器会将程序中出现内联函数的调用表达式用内联函数的函数体来替换。
- /**
- *在类里定义的成员函数会被隐含指定为内置函数
- */
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- using namespace std;
- class CStudent
- {
- public:
- void display()
- {
- cout<<"name:"<<name<<endl;
- }
- string name;
- };
- int main(int argc, char* argv[])
- {
- CStudent myStudent;
- myStudent.name="Erin";
- myStudent.display();
- return 0;
- }
<span style="font-size:18px;">/**
*在类里定义的成员函数会被隐含指定为内置函数
*/
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class CStudent
{
public:
void display()
{
cout<<"name:"<<name<<endl;
}
string name;
};
int main(int argc, char* argv[])
{
CStudent myStudent;
myStudent.name="Erin";
myStudent.display();
return 0;
}</span>
- /**
- *类外定义的函数用inline指定为内置函数
- */
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- using namespace std;
- class CStudent
- {
- public:
- inline void display();
- string name;
- };
- inline void CStudent::display()
- {
- cout<<"name:"<<name<<endl;
- }
- int main(int argc, char* argv[])
- {
- CStudent myStudent;
- myStudent.name="Erin";
- myStudent.display();
- return 0;
- }
<span style="font-size:18px;">/**
*类外定义的函数用inline指定为内置函数
*/
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class CStudent
{
public:
inline void display();
string name;
};
inline void CStudent::display()
{
cout<<"name:"<<name<<endl;
}
int main(int argc, char* argv[])
{
CStudent myStudent;
myStudent.name="Erin";
myStudent.display();
return 0;
}</span>
- /**
- *无内置函数
- *既没有在类内定义函数,也没有用inline在类外定义函数
- */
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- using namespace std;
- class CStudent
- {
- public:
- void display();
- string name;
- };
- void CStudent::display()
- {
- cout<<"name:"<<name<<endl;
- }
- int main(int argc, char* argv[])
- {
- CStudent myStudent;
- myStudent.name="Erin";
- myStudent.display();
- return 0;
- }
<span style="font-size:18px;">/**
*无内置函数
*既没有在类内定义函数,也没有用inline在类外定义函数
*/
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class CStudent
{
public:
void display();
string name;
};
void CStudent::display()
{
cout<<"name:"<<name<<endl;
}
int main(int argc, char* argv[])
{
CStudent myStudent;
myStudent.name="Erin";
myStudent.display();
return 0;
}</span>
内联函数的优点:
首先来看函数调用的实质,其实是将程序执行转移到被调用函数所存放的内存地址,将函数执行完后,在返回到执行此函数前的地方。这种转移操作需要保护现场(包括各种函数的参数的进栈操作),在被调用函数代码执行完后,再恢复现场。但是保护现场和恢复现场需要较大的资源开销。
特别是对于一些较小的调用函数来说(如上边代码中的display()函数),若是频繁调用,函数调用过程甚至可能比函数执行过程需要的系统资源更多。所以引入内联函数,可以让程序执行效率更高。
内联函数的缺点:
如果调用内联函数的地方过多,也可能造成代码膨胀。毕竟,编译器会把内联函数的函数体嵌入到每一个调用了它的地方,重复地嵌入。