在C++中使用inline关键字来定义内联函数,inline关键字放在函数定义中函数类型之前,在C++中除具有循环语句、swith语句的函数不能说明为内联函数外,其他的函数都可以说明为内联函数。
内联函数的实例:
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; inline int testLine(int a); int main(int argc, char** argv) { int a; cout <<"Please input a integer:"; cin>>a; cout<<"内联函数返回值==" <<testLine(a)<<endl; cin.get(); return 0; } inline int testLine(int a) { return a>0?a:0; }
程序中关键字inline将函数testLine说明成内敛函数,使用方法和一般函数一样,C++编译器执行到该函数的调用语句是不产生实际的函数调用,而是用该函数体替换调用表达式,使用内联函数减少了调用开销,加快了程序执行的速度,但是函数中的执行代码不能太多,结果不能太复杂,否则会增加程序代码的大小。