Bold use pointer to member functions

xiaoxiao2021-03-06  205

Bold use pointers pointing to member functions Pointing to member functions The pointers in C are more complex syntax structures, however, it is indispensable in event drivers and multithreaded environments, especially when calling member functions from the outside. In multi-thread, each thread calls this function by pointing to a pointer to the member function. If C does not have these grammar characteristics, it will encounter a lot of trouble in many cases.

Maybe you start to be intimidized by this nature, but when you are familiar with you, you will feel quite convenient, and you can simplify by using the TypeDef declaration. In this section, I will tell how to declare a pointer to the member function, assign a value to it, and call the function through this pointer.

Declare a pointer to a member function

A pointer to the member function includes the return type of the member function, with :: symbolic class name, function parameter table. Although this syntax seems to be complex, it is the same as the ordinary pointer. Pointer to the external function can be declared as follows:

Void (* pf) (char *, const char *);

Void Strcpy (Char * DEST, Const Char * Source);

PF = STRCPY;

The pointer to the member function of the corresponding class A is shown below:

Void (a :: * pmf) (char *, const char *);

The above PMF is a pointer to a member function of class A, transmitting two variables char * and const char *, no return value. Pay attention to the A :: symbol in front of the asterisk, which is consistent with the previous statement.

Value

In order to assign a value to the pointer to the member function, you can use the member function name and add a & appropriate way, the code example can be found in Listing A. Although some old compilers can be ignored, it is not allowed in standard C .

Use typedef

You can use TypeDef to hide some complex poins that point to member functions. For example, the following code defines a pointer PMA of a member function in class A and transmits a char * and const char * parameters.

Typedef void (a :: * pma) (char *, const char *);

PMA PMF = & a :: strcat; // use a typedef to define a Pointer to Member

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

New Post(0)