c++回调函数例子

#include <iostream>
#include <functional>
#include <string>
using namespace std;

class Test {
public:
	Test() {};
	~Test() {};

	// 设置请求回调
	void SetCallBack(std::function<void(const string& stock_code, const string& now_price)> cb) {
		now_price_cb_ = cb;
	}
	// 请求
	void Request(short market, const string& code) {
		now_price_cb_("222", "111");
	}
private:
	// 请求回调
	std::function<void(const string& stock_code, const string& now_price)> now_price_cb_;
	string code_;
};

class Dest {
public:
	Dest():controller_(std::make_shared<Test>()) {
		controller_->SetCallBack(std::bind(&Dest::OnCallback, this, std::placeholders::_1, std::placeholders::_2));
	};
	~Dest() {};

	void OnCallback(const string& stock_code, const string& now_price) {
		cout << "now:   " << now_price << endl;
	}

	void print() {
		controller_->Request(market_, code_);
	}

private:
	std::shared_ptr<Test> controller_;
	short market_ = -1;
	string code_ = "";
};

int main() {
	Dest d;
	d.print();
	return 0;
}

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当在C++中使用回调函数时,可以通过函数指针或函数对象来实现。以下是一个使用函数指针的简单示例: ```cpp #include <iostream> // 回调函数类型 typedef void (*CallbackFunction)(int); // 接受回调函数作为参数的函数 void performOperation(int value, CallbackFunction callback) { // 执行操作... std::cout << "Performing operation with value: " << value << std::endl; // 调用回调函数 callback(value); } // 回调函数的实现 void callbackFunction(int value) { std::cout << "Callback function called with value: " << value << std::endl; } int main() { int value = 10; // 调用函数并传递回调函数 performOperation(value, callbackFunction); return 0; } ``` 在上面的例子中,我们首先定义了一个回调函数类型`CallbackFunction`,它是一个指向返回类型为`void`、参数为`int`的函数指针。 然后,我们定义了一个名为`performOperation`的函数,它接受一个`int`类型的值和一个回调函数作为参数。在该函数内部,我们执行一些操作,并调用传递进来的回调函数。 接下来,我们定义了一个名为`callbackFunction`的回调函数,它接受一个`int`类型的值,并在被调用时打印出该值。 在`main`函数中,我们声明了一个整数变量`value`,然后调用`performOperation`函数并传递`value`和`callbackFunction`作为参数。这样,当`performOperation`函数执行完操作后,会调用传递的回调函数`callbackFunction`。 当运行上述代码时,输出结果将是: ``` Performing operation with value: 10 Callback function called with value: 10 ``` 这是一个简单的示例,展示了C++中使用函数指针实现回调函数的方法。实际应用中,可以根据需要使用不同的回调函数和参数类型来扩展和定制程序的行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值