Once in the book see function pointers related to not much attention. But recently in the actual work has been sent in handy. So I studied it carefully again.
Declaration of function pointers
It is very easy to declare a function pointer, which is to replace the function name in the function declaration with a pointer:
C + + int Test (int para1, double *para2); //function declaration int (*PF) (int para1, Span class= "Hljs-keyword" style= "Color:rgb (249,38,114)" >double *para2); //function pointer declaration
Note: You must enclose the parentheses in the declaration *pf
, because the parentheses have a higher precedence than the *
operator. So:
C + + int (*PF) (int para1, double *para2); //A pointer to a function int *pf (int para1 , double *para2); //a function that returns a pointer
The next step in declaring a function pointer is to assign a value to a function pointer. That is, the function pointer points to a type matches the function (which is consistent with the basic type of pointer), The function name of a function is the address of the function
:
c/c++PF = Test;int (*PF1) (int para1, double *para2) = test; //can also initialize
when the function pointer declaration is complete
C++11 has its own active type judgment function, which is much simpler:
C++11 Codeauto pf = test;
Calling functions using function pointers
(*pf)
The role is the same as the function name, so when you use (*pf)
it, you just need to consider it as a function name:
C + +int n = 0;double d = 0.0;int r = 0;r = (*pf)(n, &d);r = pf(n, &d); // 这样的方式C/C++也是同意的
Array of function pointers
We may also need to use an array of function pointers. The scale is as follows:
C + +intTest1 (intPARA1,Double*PARA2);//Function declarationintTest2 (intPARA1,Double*PARA2);//Function declarationintTest3 (intPARA1,Double*PARA2);//Function declarationint(*pfarray[3])(intPARA1,Double*PARA2) = {test1, test2, test3};//function pointer array declaration and initializationr = *pfarray[0] (n, &d);//Function call
It is more cumbersome to be able to see the use of function pointers in such a way. Imagine assuming that the function return value above is a const pointer, and we want to declare an array of function pointers as immutable, const
where should this be added? Here is another simple solution, which is the following to simplify using typedef .
using typedef for simplification
C + +typedef int(*p_fun) (intPARA1,Double*PARA2);//So we can use a function pointer as if it were a normal type.P_fun PF = test;ConstP_fun PF1 = test;//Constant function pointer Declaration and initialization, note the same as the general const data type. Constant function pointers must be initialized at the time of declarationP_fun pfarray[3] = {test1, test2, test3};ConstP_fun pfarray1[3] = {test1, test2, test3};//constant function pointer array declaration and initialization
It ' s that easy!
Reference book: "C + + Primer Plus (6th edition) Chinese version"
C + + Learning: function pointers