Latest web development tutorials

C ++ inline functions

C ++ Class & Objects C ++ Class & Objects

C ++inline function is often used with class.If a function is inline, then at compile time, the compiler will copy the code for the function in each place where the function is called.

Inline function to make any changes, we need to recompile all the functions of the client, because the compiler needs to be replaced once all the code, otherwise it will continue to use the old function.

If you want a function is defined as an inline function, you need to place the keywordinline in front of the function name, the function before calling function needs to be defined.If the function has been defined more than one line, the compiler will ignore the inline qualifier.

Functions defined in the class definition are inline functions, even without the use ofinline specifier.

Here is an example, using inline functions 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 ++ Class & Objects C ++ Class & Objects