C ++如何将成员函数指针传递给另一个类? [英] C++ How to pass member function pointer to another class?

查看:232
本文介绍了C ++如何将成员函数指针传递给另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我要实现的:

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

然后是名为Test的类

Then is the class named Test

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

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

Now in Test(), I want to pass OnEventStarted to Delegate like this:

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

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

But OnEventStarted is a non-static member function, how should I do?

推荐答案

要调用成员函数,既需要指向成员函数的指针,又需要对象。但是,鉴于成员函数类型实际上包括包含该函数的类(在您的示例中,它为 void(Test :: * mEventFunction)(); 并可以与仅 Test 成员,更好的解决方案是使用 std :: function 。这是这样的: / p>

In order to call a member function, you need both pointer to member function and the object. However, given that member function type actually includes the class containting the function (in your example, it would be void (Test:: *mEventFunction)(); and would work with Test members only, the better solution is to use std::function. This is how it would look like:

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));
}

这篇关于C ++如何将成员函数指针传递给另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆