1#include <iostream>2 using namespacestd;3 4 intPrintval (inti) {5cout<<i<<Endl;6 return 0;7 }8 9 intADD (intIintj) {Ten returni+J; One } A - voidCompare (intIintj) { - if(i==j) thecout<<i<<"=="<<j<<Endl; - Else if(i>j) -cout<<i<<">"<<j<<Endl; - Else +cout<<i<<"<"<<j<<Endl; - } +typedefint(*pfunc) (int); A at intMain () { -PFunc P1 =Printval; - int(*P2) (int,int); -P1 (7); -P1 = &Printval; -(*P1) (8); inP2 =Add; -COUT<<P2 (4,5) <<Endl; to +P2 = reinterpret_cast<int(*) (int,int) > (Compare);//make a strong turn - theP2 (4,5); *}
1, the Writing method type (*name) (param);
2, function pointer writing is more complex, generally use typedef to simplify.
3. The function prototype must be consistent with the prototype when the function pointer is defined, or it will cause a compilation error. However, in some special cases, you can use the reinterpret_cast operation to convert between function pointers of different types.
4, there is a function called "callback function". The callback function is a kind of dynamic application pattern which defines the function's prototype, and the function body is handed to the third party to implement. When implementing a function call, first pass the address of the callback function as one of the parameters to the key function. The callback function is invoked inside the keynote function through a function pointer. The mechanism of the callback function breaks the limit of static binding between the keynote function and the dropped function, and provides a convenient means for the user to make full use of the operating system.
C + + function pointers