C++ Inline Functions

C++ Classes & Objects

C++ Inline Functionsis usually used with classes. If a function is inline, then at compile time, the compiler places a copy of that function's code at every location where the function is called.

Any modification to an inline function requires recompiling all clients of the function, because the compiler needs to replace all the code again; otherwise, it will continue to use the old function.

If you want to define a function as an inline function, you need to place the keyword before the function name.inline, and the function must be defined before it is called. If the defined function is more than one line, the compiler will ignore the inline qualifier.

Functions defined within a class definition are all inline functions, even if the inline keyword is not used.inlinespecifier.

The following is an example that uses an inline function to return the maximum of two numbers:

#include <iostream>
 
using namespace std;

inline int Max(int x, int y)
{
   return (x > y)? x : y;
}

// 程序的主函数
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;
}

When the above code is compiled and executed, it produces the following results:

Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

C++ Classes & Objects

other extensions