成员函数指针的行为含香函数指针,但你想调用他们时,除了参数之外,你还必须传递一个对象。
class Parrot { public: void Eat() { cout << "Tsk, knick, tsk..." << endl; } void Speak() { cout << "On Captain, My Captain" << endl; } }; int main() { // Define a type: pointer to a member function of Parrot,taking no arguments and return void typedef void(Parrot::*TpMemFun) (); // Create an object of that type and initialize it with the address of Parrot::Eat TpMemFun pActivity = &Parrot::Eat; // Create a Parrot... Parrot geronimo; // a pointer to it... Parrot *pGeronimo = &geronimo; // Invoke the member function stored in Activity // via an object. Notice the user of operator.* (geronimo.*pActivity)(); // Same, via pointer. Now we use operator->* (pGeronimo->*pActivity)(); // Change the activity pActivity = &Parrot::Speak; (geronimo.*pActivity)(); return 0; }
你可以获取一般函数的 reference, 却无法获得成员函数的 reference。