Demand
Suppose you want to design a function called estimate (), estimating the time it takes to write code for a specified number of lines, and expect that function to be available to different programmers.
A portion of the code in Estimate () is the same for all users, but the function allows each programmer to provide its own algorithm to estimate time.
To achieve the goal, the mechanism used is to pass the address of the algorithm function that the programmer wants to use to estimate ().
The implementation code is as follows
Copy Code code as follows:
Funpointer.cpp: Defines the entry point for a console application.
//
#include "stdafx.h"
#include <iostream>double Betsy (int);
Double pam (int);
The second parameter of the estimate function takes a function pointer
void estimate (int lines,double (*PF) (int));
int _tmain (int argc, _tchar* argv[])
{
using namespace Std;
int code;
cout<< "How many lines of code does you need?" <<endl;
cin>>code;
cout<< "Here ' s Betsy ' estimate:" <<endl;
Estimate (Code,betsy);
cout<< "Here's Pam ' s estimate:" <<endl;
Estimate (Code,pam);
GetChar ();
GetChar ();
return 0;
}
Inline double betsy (int lines) {return 0.05*lines;}
Inline double pam (int lines) {return 0.03*lines+0.004*lines*lines;}
inline void estimate (int lines,double (*PF) (int))
{
using namespace Std;
cout<<lines<< "lines would take" << (*PF) (lines) << "hour (s)" <<endl;
}
Run results
Benefits of using function pointers
The above design is helpful for future program development. When a programmer develops its own algorithm for estimating time, he will not need to rewrite the estimate () function. Instead, he only needs to provide his own function address and make sure that the function's arguments and return type are correct.
The function pointer allows the programmer to modify the behavior of the estimate (), although he does not have access to the source code of estimate ().
inline function
Because function implementation is simpler, you can use inline functions instead of regular functions.
To use inline functions (the new features of C + + to increase the speed of your program), you must take one of the following measures:
Add keyword inline before function declaration
Add keyword inline before function definition
Internal chain functions run faster than regular functions, but at the cost of consuming more memory. If the program calls the same inline function in 10 different places, the modifier will contain 10 copies of the function code, as shown in the following illustration:
Under what circumstances should you consider using an inline function?
function code execution time is very short
If you are using a C-language macro to perform similar functions, consider converting them to C + + inline functions
Note: When a function is too large or the function is recursive, the compiler may not treat it as an inline function.