#include <iostream>
#include <string>
#include <functional>
#include <thread>
using namespace std;
using Func = function<void(int)>; //函数指针 意味着是 void A (int B){} 的函数缩写
class Driver
{
private:
Func func; //函数指针
public:
void registerCallback(Func f) //注册 ,形参是函数指针
{
func = f;
}
void start()
{
cout << "driver..." << endl;
int i = 0;
while(true)
{
func(i);
cout << "driver start:" << i++ << endl;
this_thread::sleep_for(chrono::milliseconds(10)); //睡眠10ms
}
}
};
class App
{
public:
App()
{
Func func = std::bind(&App::callback, this, std::placeholders::_1); //回调函数
Driver driver;
driver.registerCallback(func);
driver.start();
}
void callback(int i)
{
cout << "App callback:" << i << endl;
}
};
int main()
{
App app;
return 0;
}
回调函数解耦理解
最新推荐文章于 2025-08-14 11:57:11 发布
本文展示了一个使用C++实现的简单回调机制示例。通过定义函数指针并将其传递给一个类,该类会在其成员函数中调用这个外部传入的函数。此示例还演示了如何使用std::bind绑定成员函数。
2843

被折叠的 条评论
为什么被折叠?



