There are function pointers in C + +, which are declared as follows:
void (*p) (float) where p is a function pointer, if we define a function
void Fun (float) so we can assign P = fun or P = &fun to P
At the same time, there is a concept called member function pointer, which is similar to the function pointer, the difference is that it is a pointer to the member function of the class, and its reputation is as follows:
void (class_name::* p) (float) This means that P is a function pointer to a function in the Class_name class such as void Fun_name (float)
The way to assign a value is to include a show function in the Cat class
Class Cat {
Public
void Show ();
}
void (cat::* p) ();
p = &cat::show; to assign a value to P
So p points to the address where the show code fragment resides.
This can be used when calling:
Cat CAT1;
(cat1.*p) (), the show function in the Cat class is called, note that because the call operator () has a higher precedence than the * number, you need to enclose the cat1*p in parentheses.
There is also a usage that can be used to simulate a launch in Java to achieve the purpose of the callback:
For example, we have a animal class
Class Animal {}
Cat class inherits from animal
Class Cat:public Animal {
Public
void Show ();
}
Then we can make a reputation. member function pointers for a parent class
void (animal::* p) ();
The value of the member function in the subclass is actually passed when the value is assigned.
p = static_cast<void (animal::*) () > (&cat::show); Note that you need to convert with static_cast, or the compilation does not pass
When we actually go to the call, for example:
Cat CAT1;
(cat1.*p) (); The show function in the subclass is called;
This allows the member function pointers of all subclasses to be transformed into member function pointers of a common base class, thus enabling the function of the callback class member function.
C + + Learning member function pointers