我有以下情况,我有两个班。我通过回调函数将类1的实例传递给类2的实例。最终目标是连接到某些东西(比如sql server)并且可能每隔x分钟检索一些数据集。我如何修改下面的内容,以便在将类1的对象传递给类2的对象后,我可以以某种方式让对象1完成所有工作。基本上我需要实现连接到SQl并将数据放在类foo的work()函数中。更重要的是如何在main();
中将结果集中继回用户这有意义吗?是对的吗?最终的目标是锁定一个sql server并每隔5分钟获取一个数据集并生成一些统计信息以便返回给用户,如果要修改它的话?连接应该由foo类还是bar类处理
class foo{
public:
void work(int id, &result){}
};
class bar{
private:
foo* foo_
public:
void callback(foo* tempfoo){
foo_ = tempfoo;
}
void work();
};
int main(){
foo send;
bar receive;
receive.callback(&send);
//do a bunch of stuff with the receive object to get the result
bar.work(//some parameters that are needed to generate the result);
}
非常感谢你们。
答案 0 :(得分:2)
想要调用回调的类应该使用函数指针,然后在适当的时候调用该指针(当工作完成时)。
关于如何准确传递函数指针,有几个选项。您可以使用Lambda(如下面的示例代码中所示),或者您可以将std :: bind与成员函数一起使用。
以下示例:
class foo(){
public:
foo()
~foo()
work(int id, &result){
//do work
//call callback with some params
callback(PARAMS);
}
void setCallback(std::function<void(PARAMETERS)> cb){
callback = cb;
}
private:
std::function<void(PARAMETERS)> callback = nullptr;
}
class bar(){
private:
foo* foo_
public:
bar()
~bar()
work();
}
int main(){
foo send;
bar receive;
receive.setCallback([](PARAMETERS){
//your callback code in lambda
//send and receive are not captured here
//if you wish to capture send and receive
//you should somehow maintain their existence in memory
//until the callback is called, otherwise you'll get bad access error
//due to those guys already destroyed
//to capture send and receive you should put them into [] of lambda declaration.
//Append & if you want to capture by reference.
});
receive.work(//some parameters that are needed to generate the result);
}