1 Function Pointers
A pointer variable that points to the address of the function , declared as follows:
general function:void func (void);
Pointer to function func (void) the pointer:void (*pfunc) (void) = Func;
where (*func) must have parentheses, otherwise the compiler will consider a func (void) function that returns a type of void*.
1#include <iostream>2 using namespacestd;3 4 intarray[Ten];5 6 //1 Defining an array type7typedefint(arraytype) [Ten];8 9 //2 Defining an array pointer typeTentypedefint(*parraytype) [Ten];//Note the step of the pointer One A //3 Function Pointers - intFuncinta) - { thecout <<"the values passed in are:"<< a <<Endl; - returnA; - } - + //3.1 Defining function Types -typedefint(Functype) (int); + //3.2 directly define function pointers A int(*pfunc) (int) =func; at //3.3 Defining a pointer type to a function type -typedefint(*PF) (int); - - //3.4 When a function pointer is a function parameter, the called function invokes the external function through this pointer, thus forming a callback - intLibfun (int(*PFF) (inta)) - { in intx; -x =10000; to PFF (x); + } - the intMain () * { $cout <<"Hello, func pointer ..."<<Endl;Panax Notoginseng //1 -ArrayType array;//equivalent to int array[10]; thearray[0] =1; + //2 A Parraytype p; thep = &array;//can also be directly defined: Int (*p) [Ten] = &array; +(*p) [1] =2; - $ //3.1 Defining a pointer to a function with a function type $functype* fp =NULL; -fp = func;//The function name represents the entry address of the function (note: Func==&.&. ( &func) ==*.*. (*func)) - //calling a function from a function pointer thefp5); - Wuyi //3.2 thePfuncTen); - Wu //3.3 -PF PF =func; About(*PF) ( the); $ - //3.4 - int(*PFF) (inta) =func; - Libfun (PFF); A + return 0; the}
2 Function Objects
The first thing you need to make clear is that the function object is an object , an instance of a class , except that the object has the function of a function . When implemented, only the () operator of this object can be overloaded:
1#include <iostream>2 using namespacestd;3 4 classDemo5 {6 Public:7 int operator ()(intx) {returnx;}8 };9 Ten intMain () One { A Demo D; -cout << D (+) <<Endl; - the return 0; -}
A function object in C + + can be analogous to a function pointer in C, in general, where a function pointer is used in C + +, a function object can be substituted in C + +:
#include <iostream>using namespacestd;classdemo{ Public: int operator()(intx) {returnx;} Public: Template<typename t>T operator () (t T1, T T2) {cout<< T1 <<" + "<< T2 <<" = "<< T1 + T2 <<Endl; returnT1 +T2; }};template<typename t>t AddT (t T1, T T2, demo& DD)/* Function object passed as function parameter */{ returnDD (t1, t2);}intMain () {Demo D; cout<< D ( -) <<Endl; Demo DD; /* Define Function Object */AddT (+, DD); /* Use of Function objects * /AddT (100.5,200.7, DD); return 0;}
function pointers and Function objects