i'm confused about how to do inline functions in C++....
lets say this function. how would it be turned to an inline function
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
开发者_如何转开发
In order to turn it into an inline function you need to do two things:
- Declare it inline by using keyword
inline
. - Make sure that the definition of this function is visible in every translation unit where it is used. This normally means that you have to put the entire definition of the function into a header file.
As others have said, you can use the inline
keyword to tell the compiler you want your function inlined. But the inline
keyword is just a compiler hint. The compiler can and will chose to ignore your request if it wants or needs to.
An alternative is to make your function a function template, which will often be blown out inline:
template<class Val>
Val maximum( Val x, Val y, Val z )
{
Val max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
To post Neils answer as an actual answer:
inline int maximum(int x, int y, int z)
....
If that function definition appears inside a class {}
definition, then it is automatically inline already.
Otherwise, as others say, put inline
infront.
To make the function inline use the inline keyword:
inline int maximum( int x, int y, int z ) // note the inline keyword
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
If the function is a member of a class/struct then simply defining it inside the class (as apposed to outside it) makes it inline.
Say you have the call:
int f = maximum(3, 4, 5)
The compiler might expands the call to something like:
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
int z = max;
There's some overhead to calling a function, so inline functions give you the convenience of functions along with the performance of C macros. But that's not to say you should always use them, in most cases the compiler is better at deciding when optimizations like this are needed and might not even honor your request.
You can read more about inline functions and how (and when) to use them at C++ FAQ Lite and this GotW
inline
just tells the compiler that you want the function code copied everywhere it is refernece, it makes the code a bit faster (no function call overhead) but bigger (the code is copied). This page is more in depth.
精彩评论