gpt4 book ai didi

c++ - 如何设置适当的回调来检索数据

转载 作者:太空狗 更新时间:2023-10-29 21:42:35 24 4
gpt4 key购买 nike

我有以下情况,我有两个类(class)。我通过回调函数将类 1 的实例传递给类二的实例。最终目标是连接到某个东西(比如 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);
}

非常感谢你们。

最佳答案

想要调用回调的类应该采用函数指针,然后在适当的时候(工作完成时)调用该指针。

关于如何准确传递函数指针,有几个选项。您可以使用 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);
}

关于c++ - 如何设置适当的回调来检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com