/*
function pointer related usage
*/
1 #define_crt_secure_no_warnings2 #defineHOME3 //#define NDEBUG4#include <iostream>5#include <stdexcept>6#include <cassert>7#include <ctype.h>8#include <locale>9#include <iterator>Ten#include <cmath> One#include <string> A#include <vector> -#include <initializer_list> -#include <ctime> the using namespacestd; - usingPtrfun =int(*) (int,int); - - intMyadd (intXinty) + { - return(x +y); + } A intMySub (intXinty) at { - return(X-y); - } - - intMymul (intXinty) - { in return(x *y); - } to + intMydiv (intXinty) - { the if(0==y) * { $Std::cerr <<"error: Divide by 0"<<Endl;Panax Notoginseng return-1; - } the Else + { A return(X/y); the } + } - $ voidCompute (intXintYint(*p) (int,int)) $ { -cout << p (x, y) <<Endl; - } the - Wuyi intMainintargcChar**argv) the { - #ifdef HOME Wu //freopen ("in", "R", stdin); - //freopen ("Out", "w", stdout); About #endif $ -cout <<"method One:"<<Endl; - //the following two ways of declaring it are also possible - //Vector<int (*) (int, int) > Vecfunc; A //vector<ptrfun> Vecfunc; +Vector<decltype (Myadd) *>Vecfunc; the Vecfunc.push_back (myadd); - Vecfunc.push_back (mysub); $ Vecfunc.push_back (Mymul); the Vecfunc.push_back (mydiv); the for(inti =0; I < vecfunc.size (); ++i) the { thecout << Vecfunc[i] (6,3) <<Endl; -cout << (*vecfunc[i]) (6,3) <<Endl; inCompute (6,3, Vecfunc[i]); the } the Aboutcout << Endl <<"Method Two:"<<Endl; theDecltype (myadd) *p1 = myadd, *p2 = mysub, *p3 = Mymul, *P4 =mydiv; theVector<decltype (myadd) *> Vec1func ={p1, p2, p3, p4}; the for(inti =0; I < vec1func.size (); ++i) + { -cout << Vec1func[i] (6,3) <<Endl; thecout << (*vec1func[i]) (6,3) <<Endl;BayiCompute (6,3, Vec1func[i]); the } the - #ifdef HOME -Std::cerr <<"Time Elapsed:"<< clock ()/Clocks_per_sec <<"Ms"<<Endl the<<"message:"<< __file__ <<Endl the<<": in function"<<__func__ the<<" at line"<< __line__ <<Endl the<<"Compiled on"<<__date__ -<<" at"<< __time__ <<Endl; the #endif the return 0; the}
The use of function pointers in the learning of C + + Primer