class A { int _val; int val(); }; int (A::*p_val) = &A::_val; int ( A::*p_func )() = &A::val;
Pointer to class members, which is rarely used in the impression. When I re-learn C ++, I found that I ignored a very important thing, I used to think that the member functions of the class cannot be used as Callback functions. Therefore, many C Programs cannot be transplanted to C ++ until now, this is because you do not know the pointer to a class member.
1. pointer to non-static members
In fact, it is easy to point to non-static class members. The only difference between them and common pointers is that they are restricted by classes. As follows:
As you can see, yes. The difference with a normal pointer is that the pointer to a class member must also carry the class. In the above example, :: put this qualifier together, then? The usage is the same as that of normal pointers.
2. pointer to a static member
Pointer to a static member. The declaration method is exactly the same as that of a normal pointer, but the class qualifier must be added when values are assigned. Why? I think it can be understood that the existence of non-static members depends on the class. When the class disappears, non-static members die. Therefore, the declaration must be tied to the class qualifier, static members are not attached to the class. Therefore, the class qualifier is not required. As follows:
class A { static int _val; static int val(); }; int *p_val = &A::_val; int (*p_func) = &A::val;
3. Benefits:
One advantage is that by pointing to a member's function pointer, you can easily call each member function. Another advantage is that for a static member function, you can become a callback function in C.
The following is an example to further understand:
#include <iostream> #include <string> using namespace std; typedef void (*funchandler)(); void register_func(funchandler f) { cout << "register_func" << endl; (*f)(); } class A { public: A() : _val( 0 ) { cout << "create A..." << endl; } void test() { cout << "test..." << endl; } void test1() { cout << "test1..." << endl; } void test2() { cout << "test2..." << endl; } int val() { return _val; } static void test3() { cout << "test3..." << endl; } int _val; private: }; int main() { A a; int ( A::*p_val ) = 0; p_val = &A::_val; cout << "a.*p_val: " << a.*p_val << endl; void (A::*p_func)(); p_func = &A::test; a.test(); (a.*p_func)(); p_func = &A::test1; ( a.*p_func )(); p_func = &A::test2; ( a.*p_func )(); void (* pp_func)(); pp_func = &A::test3; (*pp_func)(); register_func( pp_func ); return 0; }