且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将对象的方法传递给外部函数

更新时间:2023-11-09 23:18:04

这是成员函数的指针:

void whatToDo(myClass& myObj, void (myClass::*p)())
{
    // p is a pointer to a member function class myClass that
    // takes no arguments and returns void

    // you can invoke it thusly
    (myObj.*p)();
}

您可以提供以下指针:

struct myClass {
    void doThis();
    void doThat();
};

myClass c;
whatToDo(c, &myClass::doThis); // will invoke c.doThis();
whatToDo(c, &myClass::doThat); // will invoke c.doThat();