function Pointersfunction pointers: pointer variables to functions, when C compiles, each function has an entry address, then a function pointer to that function points to that address. function pointers have two main functions: used as arguments for calling functions and functions.
Int (*func) (int x);
such as the above code this is a function pointer, the code (*FUNC) in parentheses is required, which tells the compiler that this is a function pointer instead of declaring a function with the return type as a pointer, the following parameters if the function is pointed to the function parameters. Use code such as the following:
#include <iostream>using namespace Std;int (*func) (int a, int b); int bar (int a, int b) {return a + B;} int foo (int a, int b) {return A;} int _tmain (int argc, _tchar* argv[]) {func = Bar;cout << func (+) << endl;system ("pause"); func = foo;cout & lt;< func << endl;system ("pause"); return 0;}
Such statements are cumbersome and can actually be simplified using typedef:
#include <iostream>using namespace Std;typedef int (*PF) (int, int),//int (*func) (int a, int b); int bar (int a, int b) {R Eturn A + b;} int foo (int a, int b) {return A;} int _tmain (int argc, _tchar* argv[]) {PF Func;func = bar;cout << func () << endl;system ("pause"); func = fo O;cout << func (a) << Endl;system ("pause"); return 0;}
The function pointer is also used as a function parameter, you can pass in the function pointer in the formal parameter list of a function, and then the side can use this function pointer to the function, so that the edge can make the program more clear and concise.
#include <iostream>using namespace Std;typedef int (*PF) (int, int),//int (*func) (int a, int b); int bar (int a, int b) {R Eturn A + b;} int foo (int a, int b) {return A;} void func (int a, int b, PF ptr) {cout << ptr (A, b) << Endl;return;} int _tmain (int argc, _tchar* argv[]) {PF ptr;ptr = Bar;func (n, A, PTR), System ("pause");p tr = Foo;func (n, V, PTR); system ("pause"); return 0;}
pointer FunctionsThe definition that distinguishes a function pointer should be a pointer function, which is essentially a function that refers to a function that returns a function as a pointer, usually a function of the form:
int* func (int x,int y);
In fact, the return value is a pointer to the function, this as long as remember what form on the line, not difficult to understand.
C + + pointer functions and function pointers