[英]C++ Pass a member function to another class
我正在尝试使用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*/
}
}
我知道通常您希望使用类似B::callBackFunction
类来定义AddCallback
的标头,但是我确实需要在B
导入A
,因此让两个类相互导入将很尴尬。 我知道我以前见过,但语法不正确
这是使用静态成员函数的一个选项:
#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);
};
您必须调用void A :: AddCallback并传递回调,而不是在childObject(MyCallBackFunction)中传递参数;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.