Rule 1: * it needs to be combined with indirectly referenced objects. Because there is no address in the class, the member pointer only indicates a certain offset in the object.
Rule 2: when getting the member function address (offset address), the symbol & is necessary, which is different from the usage of the non-member function pointer.
Case 1:
//: PointerToMemberData. cpp
# Include <iostream>
Using namespace std;
Class Data
{
Public:
Int a, B, c;
Void print () const
{
Cout <"a =" <a <", B =" <B
<", C =" <c <endl;
}
};
Int main ()
{
Data d, * dp = & d;
Int Data: * pmInt = & Data:;
Dp-> * pmInt = 47; // Rule 1
PmInt = & Data: B;
D. * pmInt = 48;
PmInt = & Data: c;
Dp-> * pmInt = 49; // Rule 1
Dp-> print ();
}
Case 2: www.2cto.com
//: PointerToMemberFunction. cpp
# Include <iostream>
Using namespace std;
Class Widget
{
Public:
Void f (int) const {cout <"Widget: f () \ n ";}
Void g (int) const {cout <"Widget: g () \ n ";}
Void h (int) const {cout <"Widget: h () \ n ";}
Void I (int) const {cout <"Widget: I () \ n ";}
};
Int main ()
{
Widget w;
Widget * wp = & w;
Void (Widget: * pmem) (int) const = & Widget: h; // Rule 2
(W. * pmem) (1); // Rule 1
(Wp-> * pmem) (2); // Rule 1
}
Case 3:
//: PointerToMemberFunction2.cpp
# Include <iostream>
Using namespace std;
Class Widget
{
Void f (int) const {cout <"Widget: f () \ n ";}
Void g (int) const {cout <"Widget: g () \ n ";}
Void h (int) const {cout <"Widget: h () \ n ";}
Void I (int) const {cout <"Widget: I () \ n ";}
Enum {cnt = 4 };
Void (Widget: * fptr [cnt]) (int) const;
Public:
Widget ()
{
Fptr [0] = & Widget: f; // Rule 2
Fptr [1] = & Widget: g;
Fptr [2] = & Widget: h;
Fptr [3] = & Widget: I;
}
Void select (int I, int j)
{
If (I <0 | I> = cnt)
Return;
(This-> * fptr [I]) (j); // rule 1, this is required
}
Int count () {return cnt ;}
};
Int main ()
{
Widget w;
For (int I = 0; I <w. count (); I ++)
W. select (I, 47 );
}
Author: yucan1001