目录

内联函数(Inline Functions)

C ++ inline函数是通常用于类的强大概念。 如果函数是内联函数,则编译器会在编译时调用函数的每个位置放置该函数的代码副本。

对内联函数的任何更改都可能需要重新编译函数的所有客户端,因为编译器需要再次替换所有代码,否则它将继续使用旧功能。

要内联函数,请在函数名称前面放置关键字inline ,并在对函数进行任何调用之前定义函数。 如果定义的函数超过一行,编译器可以忽略内联限定符。

类定义中的函数定义是内联函数定义,即使不使用inline说明符也是如此。

以下是一个示例,它使用内联函数返回最多两个数字 -

#include <iostream>
using namespace std;
inline int Max(int x, int y) {
   return (x > y)? x : y;
}
// Main function for the program
int main() {
   cout << "Max (20,10): " << Max(20,10) << endl;
   cout << "Max (0,200): " << Max(0,200) << endl;
   cout << "Max (100,1010): " << Max(100,1010) << endl;
   return 0;
}

编译并执行上述代码时,会产生以下结果 -

Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
↑回到顶部↑
WIKI教程 @2018