How do I declare and use a pointer to a class member function?

How do I declare and use a pointer to a class member function? (top)

The syntax is similar to a regular function pointer, but you also have to specify the class name. Use the .* and ->* operators to call the function pointed to by the pointer.
Collapse

class CMyClass
{
public:
  int AddOne ( unsigned n ) { return n+1; }
  int AddTwo ( unsigned n ) { return n+2; }
};
main()
{
     CMyClass myclass, *pMyclass = &myclass;
     int (CMyClass::* pMethod1)(unsigned);    // Full declaration syntax
     pMethod1 = CMyClass::AddOne;           // sets pMethod1 to the address of AddOne
     cout << (myclass.*pMethod1)( 100 );    // calls myclass.AddOne(100);
     cout << (pMyclass->*pMethod1)( 200 );  // calls pMyclass->AddOne(200);
     pMethod1 = CMyClass::AddTwo;           // sets pMethod1 to the address of AddTwo
     cout << (myclass.*pMethod1)( 300 );    // calls myclass.AddTwo(300);
     cout << (pMyclass->*pMethod1)( 400 );  // calls pMyclass->AddTwo(400);

    //Typedef a name for the function pointer type.
    typedef int (CMyClass::* CMyClass_fn_ptr)(unsigned); 
    CMyClass_fn_ptr pMethod2;
    // Use pMethod2 just like pMethod1 above....
}

The line Collapse
int (CMyClass::* pMethod1)(unsigned);
pMethod1 is a pointer to a function in CMyClass; that function takes an unsigned parameter and returns an int.

Note that CMyClass::AddOne is very different from CMyClass::AddOne(). The first is the address of the AddOne method in CMyClass, while the second actually calls the method.

原文地址:https://www.cnblogs.com/tianfu/p/1706526.html