inline函数
什么是inline function?
在class body中完成定义的函数会自动成为inline function的候选人,注意这个词-候选人,最后能不能当选inline还不一定!
在class body外定义的,如果定义前加inline字眼,那它也会成为inline function的候选人。
那就有疑问了,那什么样的函数最后一定会当选inline function呢?我们知道c中的宏定义其实是一种预编译指令,比如#define PI 3.1415926 ,它的作用是预编译阶段将程序中的所有PI 替换成 3.1415926。inline function其实跟这个有异曲同工之妙,比如我们设计了一个people类。
void print(string str);
class People
{
private:
int age_;
string name_;
string country_;
public:
People(int age, string name, string country)
:age_(age),name_(name),country_(country)
{}
inline void printName()
{
print(name_);
}
inline void printCountry()
{
print(country_);
}
};
inline void print(string str)
{
cout << str << endl;
}
类内的函数,printName() 与 printCountry(),因为写在了类内,因此自动成为 inline 函数的候选人,所以,在前面加 inline 是没啥必要的(当然加上也无所谓)。
类外的函数,print(string str) 函数,因为短小精悍,我们在前面加上 inline 字样,是想让它成为 inline 函数候选人,当然,最后能不能当选 inline 函数,取决于编译器。print 函数如此简单,想必编译器会让它成为 inline 函数的吧。
print(string str) 如果真正成为 inline 函数,在预编译阶段会发生什么?其实上面也说了,inline 函数与宏定义有异曲同工之妙。所以在预编译阶段,上面的printCountry() 函数会预编译为:
inline void printCountry()
{
//print(country_);
cout << str << endl;//替代了上面的函数
}
这就是 inline 函数的精髓。
不对之处,还望指正!