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

C++ How to pass member function pointer to another class?

本文关键字:另一个 指针 函数 成员 C++      更新时间:2023-10-16

这是我想要实现的:

class Delegate
{
public:
    void SetFunction(void(*fun)());
private:
    void(*mEventFunction)();
}

然后是名为 Test 的类

class Test
{
public:
    Test();
    void OnEventStarted();
}

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

Test::Test()
{
    Delegate* testClass = new Delegate();
    testClass->SetFunction(this::OnEventStarted);
}

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

为了调用成员函数,您需要指向成员函数和对象的指针。但是,鉴于成员函数类型实际上包括包含函数的类(在您的示例中,它将是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));
}

你应该传递&Test::OnEventStarted,这是成员函数指针的正确语法

之后,您必须获取 Test 类的实例才能像这样运行函数。

instanceOfTest->*mEventFunction()