A simple example:
#include <iostream>using namespacestd;intSumintXinty) { returnX +y;}intMain () {cout<< sum (1,2) <<Endl; int(*PF) (int,int);//not initializedPF =sum; cout<< PF (3,4) <<Endl; /*Output:3 7*/ return 0;}
In case of overloading, the compiler precisely matches the function by pointer type.
#include <iostream>using namespacestd;intSumintXinty) { returnX +y;}intSumintXDoubley) {cout<<"sum2"<<Endl; returnX +y;}intMain () {cout<< sum (1,2) <<Endl; int(*PF) (int,int);//not initializedPF =sum; cout<< PF (3,4) <<Endl; /*Output:3 7*/ return 0;}
To use a function as an argument:
#include <iostream>using namespacestd;intSumintXinty) { returnX +y;} typedef decltype (SUM) func;intUseInt2 (intXintY, func f) { returnf (x, y);}intMain () {cout<< UseInt2 (3,4, sum) <<Endl; /*output = 7*/ return 0;}
The return type is not automatically converted to a pointer, we must display the return type as a pointer, but I think the return function is useless unless it is inside the function that can also be used to construct functions such as Python.
Practice
6.54
#include <iostream> #include <vector> using namespace STD; int sum (int x, int y) { return x + y;} int main () { using pf = int (*) (int , int <pf> Pfvec; return 0 ;}
6.55 & 6.56
#include <iostream>#include<vector>using namespacestd;intAddintXinty) { returnX +y;}intSubtractintXinty) { returnX-y;}intMultiplyintXinty) { returnX *y;}intDivideintXinty) { returnX/y;}intMain () {usingPF =int(*) (int,int); Vector<pf>Pfvec; Pfvec.push_back (add); Pfvec.push_back (subtract); Pfvec.push_back (multiply); Pfvec.push_back (divide); for(pf F:pfvec) {cout<< F ( A,4) <<Endl; } return 0;}
Output Result:
- 8 - 3
"C + + Primer, 5e" function pointer