C++如何将成员函数指针传递给另一个类?

Yon*_*hui 4 c++

这是我想要意识到的:

class Delegate
{
public:
    void SetFunction(void(*fun)());
private:
    void(*mEventFunction)();
}
Run Code Online (Sandbox Code Playgroud)

然后是名为Test的类

class Test
{
public:
    Test();
    void OnEventStarted();
}
Run Code Online (Sandbox Code Playgroud)

现在在 Test() 中,我想像这样将 OnEventStarted 传递给委托:

Test::Test()
{
    Delegate* testClass = new Delegate();
    testClass->SetFunction(this::OnEventStarted);
}
Run Code Online (Sandbox Code Playgroud)

但是 OnEventStarted 是一个非静态成员函数,我该怎么办?

Ser*_*eyA 6

为了调用成员函数,您需要指向成员函数和对象的指针。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它将仅void (Test:: *mEventFunction)();Test成员一起使用,更好的解决方案是使用std::function。这就是它的样子:

class Delegate {
public:
    void SetFunction(std::function<void ()> fn) { mEventFunction = fn);
private:
    std::function<void ()> fn;
}

Test::Test() {
    Delegate testClass; // No need for dynamic allocation
    testClass->SetFunction(std::bind(&Test::OnEventStarted, this));
}
Run Code Online (Sandbox Code Playgroud)

  • C11 中有一个新的 `std::mem_fn`。我相信这样更好。 (2认同)