About C + +The use of function pointers in (contains a discussion of typedef usage) (a) The application of simple function pointers. //Form 1: return type (* function name) (parameter table)Char(*pfun) (int); CharGlfun (intA) {return;} voidMain () {Pfun=Glfun; (*pfun) (2); The first line defines a pointer variable pfun. First we recognize that it is a pointer to a function, according to the "Form 1" mentioned earlier, which is an int and the return value is a char type. Only the first sentence we can not use this pointer, because we have not yet assigned to it. The second line defines a function glfun (). The function is exactly a function that returns char as an int parameter. We want to understand the function from the level of the pointer-the function name of the function is actually a pointer, and the function name points to the first address of the function's code in memory. Then there is the lovely main () function, and the first sentence you should understand-it assigns the address of the function Glfun to the variable pfun. In the second sentence of the main () function, "*Pfun "is obviously taking the content of the address pointed to by Pfun, of course, is to take out the contents of function Glfun (), and then given a parameter of 2. (b) The use of TypeDef is more intuitive and convenient. //form 2:typedef return type (* new type) (parameter table)typedefChar(*ptrfun) (int); Ptrfun Pfun; CharGlfun (intA) {return;} voidMain () {Pfun=Glfun; (*pfun) (2); The function of a typedef is to define a new type. The first sentence defines a type of ptrfun, and defines the type as a pointer to a function that takes an int as an argument and returns a char type. You can use the Ptrfun in the same way as with Int,char. The second line of code uses this new type to define the variable pfun, which can be used as if it were in Form 1. (iii) in C++A function pointer is used in a class. //form 3:typedef return type (class name::* new Type) (parameter table)classCA { Public: CharLcfun (intA) {return; } }; CA CA; typedefChar(CA::* ptrfun) (int); Ptrfun Pfun; voidMain () {Pfun=Ca::lcfun; ca. (*pfun) (2); Here, the pointer is defined and used with a "class restriction" or "object", which indicates that the function that the pointer is pointing to is the class object of that class, or it can be obtained using new. For example: CA*PCA =NewCA; PCA(*pfun) (2); DeletePCA; And this class object pointer can be a member variable inside the class, and you can even use the this pointer. For example: Class CA has member variable ptrfun m_pfun; voidca::lcfun2 () {( This->*m_pfun) (2); In a word, using a class member function pointer must have a "->* "or". * "is called.
Reprinted from: http://www.cnblogs.com/gmh915/archive/2009/09/30/1576996.html
About the use of function pointers in C + +