The use of function pointers in C ++ (containing discussions to TypeDef usage)

xiaoxiao2021-03-05  33

(1) Simple function pointer application. // Form 1: Return type (* function name) (parameter table) Char (* pfun) (int); char GLFUN (INT A) {Return;} void main () {PFUN = GLFUN; (* PFUN) (2 The first line defines a pointer variable PFUN. First we recognize the "Form 1" mentioned above, it is a pointer to a function, which is an INT type, and the return value is a CHAR type. Only the first sentence we can't use this pointer because we have not assigned it. The second line defines a function GLFUN (). This function is exactly a function that returns a CHAR with INT as a parameter. We have to understand the function of the function - the function name of the function - the function name is actually a pointer, and the function name points to the first address of the code in memory. Then the lovely main () function, its first sentence you should understand - it assigns the address of the function GLFU to the variable PFUN. The "* pfun" in the second sentence of the main () function is clearly the content of the address pointing to the PFUN, and of course, the content of the function GLFUN () is taken, and then the given parameter is 2. (2) It is more convenient to use TypeDef. // Form 2: typedef Return Type (* New Type) TypeDef Char (* Ptrfun) (int); Ptrfun Pfun; char GLFUN (INT A) {Return;} void main () {pfun = GLFUN; * PFUN) (2);} TypeDef's function is to define a new type. The first sentence is to define a type of PTRFUN and define this type to point to a pointer to a function. This function is parameter with an int as a parameter and returns a char type. Behind it is possible to use Ptrfun as using int, char. The second line of code uses this new type to define the variable PFUn, which can be used in the form of formula 1. (3) Use the function pointer in the C class. // Form 3: TypeDef Return Type (Class Name :: * New Type) (Parameter Table) Class Ca {Public: Char Lcfun (INT A) {Return;}}; CA CA; TypedEf Char (Ca :: * Ptrfun) (int); ptrfun pfun; void main () {pfun = ca :: lcfun; ca. (* pfun) (2);} Here, the definition and use of pointers plus "class restriction" or "object" The function used to indicate that the pointer points to the class object can also be obtained by using new NEW. For example: CA * PCA = New CA; PCA -> (* PFUN) (2); DELETE PCA; and this class object pointer can be an internal member variable, you can even use the THIS pointer. For example: class CA has a member variable Ptrfun M_PFUN; Void Ca :: LCFUN2 () {(this -> * m_pfun) (2);} In one sentence, using class member function pointer must have "-> *" or ". *" Call.

转载请注明原文地址:https://www.9cbs.com/read-34015.html

New Post(0)