Demand:
In Class A, there is a set of functions with the same specification;
Class B has a pointer to member F in a member function, initializes the member F when constructing a B object, and then calls the function of the function pointer in the DO function.
What needs to be done to achieve this goal.
Class A |
Void F1 (); |
Void F2 (); |
Void F3 (); |
|
Class B |
B (f) |
Do () { F (); } |
F A * PA; |
|
One feature of C + + is needed here: a member function pointer. This feature is generally rarely used, so the feeling is more obscure, using the following points:
1. Use a typedef to define the type of a member function pointer:
typedef void (A::* FunC) ();
This defines the Func as a null return value type in Class A and a null function pointer for the argument list.
2. Statement in B
FunC F;//To declare F as a pointer to a member function in a.
3. Declare the constructor of B
B (* A, Func f) {PA = A; f = f;}
4. Do in the following call:
(pa->*f) ();
5. Externally constructs a, B objects, and makes method calls.
A A;
B B1 (&a, &A::F1);
B1. Do (); This will call the F1.
B B2 (&a, &A::F2);
B2. Do (); This will call the F2.
Special Note:
C + + member functions implicitly have a this argument, that is, to invoke the Class object's member function, you must first have the object of the class, and therefore, in B's constructor to pass a object address in.