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

时间:2016-06-13 13:30:59

标签: c++

这是我想要实现的:

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

然后是名为Test

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

现在在Test()中,我想将OnEventStarted传递给Delegate,如下所示:

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

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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

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

之后,你必须得到一个Test类的实例来运行像这样的函数

instanceOfTest->*mEventFunction()