C ++将成员函数传递给另一个类

时间:2016-02-26 00:58:10

标签: c++

我正在尝试在C ++中进行简单的回调,但我正在按照自己的意愿进行操作。

基本上我想要这样的东西:

class A{
   void A::AddCallback(void (*callBackFunction)(string)){
      /*Code goes here*/
   }
}

和B级

#include "A.h"
class B{
   B::B(){
      A childObject;
      childObject(MyCallBackFunction);   
   }
   B::MyCallBackFunction(string arg){
      /*Code goes here*/
   }
}

我知道您通常希望使用AddCallback之类的内容定义B::callBackFunction的标头,但我需要在A中导入B所以我会这样做两个类互相导入都很尴尬。我知道我以前见过这个,但是我的语法不能正确

2 个答案:

答案 0 :(得分:4)

以下是使用静态成员函数的一个选项:

#include <string>

struct A
{
    void AddCallback(void (*cb)(std::string));
};

struct B
{
    A a;

    B() { a.AddCallback(&B::MyFun); }

    static void MyFun(std::string);
};

如果您需要非静态成员函数,那么首先需要确定要调用成员函数的B实例。例如,要在构造函数注册回调的对象上调用它:

#include <functional>
#include <string>

struct A
{
    void AddCallback(std::function<void(std::string)>);
};

struct B
{
    A a;

    B() { a.AddCallback(std::bind(&B::MyFun, this, std::placeholders::_1)); }

    void MyFun(std::string);
};

答案 1 :(得分:-1)

你必须调用void A :: AddCallback并传递回调而不是在childObject中传递参数(MyCallBackFunction);