内联函数可避免函数调用开销。因为内联函数将在程序每个调用点上“内联地”展开,如cout << IsIntEqual( 10, 10 ) << endl;在编译时将展开为cout << (static_cast<bool>(a==b)。
inline bool IsIntEqual( int a, int b ) { return static_cast<bool>( a == b ); }内联函数适用于优化小的,只有几行的而且经常被调用的函数。把内联函数放入头文件。内联函数的定义对编译器而言必须是可见的,仅有函数原型是不够的;因为内联函数会在调用处展开,所有只要使用了内联函数的地方,就有一份内联函数的代码,把内联函数放入头文件,能保证所有调用的地方展开的代码是相同的;在头文件中加入或修改内联函数,使用了此头文件的所有源文件必须重新编译。普通函数的内联只需要在函数返回值前加上关键字inline即可。内联函数的前向声明关键字inline好像可以省略(编译运行没问题,未深度证实)
//前身声明 inline bool IsIntEqual( int a, int b ); bool IsIntEqual( int a, int b ); int main() { cout << IsIntEqual( 10, 10 ) << endl; return 0; } inline bool IsIntEqual( int a, int b ) { return static_cast<bool>( a == b ); }例子:
class InlineTest { public: //在类声明中定义函数,隐式地成为内联函数 int get1() const { return 1; } //显示指定inline,定义在类声明外部 inline int get2() const; //类声明中未指定inline,但在类声明外部会显示指定 int get3() const; //在类声明及类声明外部都显示指定 inline int get4() const; }; int InlineTest::get2() const { return 2; } inline int InlineTest::get3() const { return 3; } inline int InlineTest::get4() const { return 4; }函数模板可以用与非模板函数一新的方式声明为inline,规则也一样。说明符放在形参表之后,返回类型之前,不能放在关键字template之前,
template<class T> class InlineTest { public: //在类声明中定义函数,隐式地成为内联函数 T get1() const { return 1; } //指定inline,定义在类声明外部 inline T get2() const; //类声明中未指定inline,但在类声明外部会指定 T get3() const; //在类声明及类声明外部都指定 inline T get4() const; }; template<class T> T InlineTest<T>::get2() const { return 2; } template<class T> inline T InlineTest<T>::get3() const { return 3; } template<class T> inline T InlineTest<T>::get4() const { return 4; }