本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ 回调函数
原文链接:https://www.stubbornhuang.com/915/
发布于:2020年09月23日 16:43:10
修改于:2020年10月31日 16:44:14

回调函数其实就是以函数指针做函数参数传递给另一个函数,在另一个函数执行的时候可以根据函数指针执行回调函数的代码。
以下介绍两种回调函数的形式,
- 一种是简单的以函数指针传递的形式
- 另一种是C++11特性的std::bind和std::function来实现更加简单的回调函数
1 函数指针
简单示例,便于理解,防止遗忘。
#include <iostream>
typedef double (*CallbackFunction)(double a, double b); // 回调函数指针
void CallCallbackFunction(CallbackFunction p_Function) // 调回调函数
{
CallbackFunction tempCallFunction = NULL;
tempCallFunction = p_Function;
double sum = tempCallFunction(1, 3);
std::cout << "CallbackFunction 的回调结果=" << sum << std::endl;
}
double Add(double a, double b) // 回调函数
{
return a + b;
}
int main()
{
CallCallbackFunction(Add);
getchar();
return 0;
}
2 std::bind和std::function实现回调函数
简单示例,避免遗忘
#include <iostream>
#include <functional>
#include <memory>
#include <thread>
using namespace std;
typedef std::function<void(int a,int b)> AddFunc;
class A
{
public:
typedef std::shared_ptr<A> ptr;
A()
{
};
virtual~A()
{
};
public:
void SetAddFunc(AddFunc func)
{
m_AddFunc = func;
}
void AddThread()
{
std::shared_ptr<std::thread> threadPtr = std::make_shared<std::thread>([this]() {
int count = 0;
while (count<10)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if (m_AddFunc != nullptr)
{
m_AddFunc(1, 2);
count += 1;
}
}
});
threadPtr->join();
}
private:
AddFunc m_AddFunc;
};
class B
{
public:
B()
{
if (m_pAPtr == nullptr)
{
m_pAPtr = std::make_shared<A>();
if (m_pAPtr != nullptr)
{
m_pAPtr->SetAddFunc(std::bind(&B::AddFuncCallback, this, std::placeholders::_1, std::placeholders::_2));
m_pAPtr->AddThread();
}
}
};
virtual~B()
{
}
private:
void AddFuncCallback(int a, int b)
{
std::cout << "A的函数回调" << std::endl;
};
private:
A::ptr m_pAPtr;
};
int main()
{
B t_B;
return 0;
}
当前分类随机文章推荐
- C++11 - 解析并获取可变参数模板中的所有参数 阅读403次,点赞0次
- C++ - queue存储动态指针时正确释放内存 阅读3531次,点赞2次
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读1659次,点赞0次
- C++11 - 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用 阅读1680次,点赞0次
- C++11 - 基于无锁队列的单生产者单消费者模型 阅读3565次,点赞1次
- C++ - GBK编码下的全角字符转半角字符 阅读562次,点赞0次
- C++ - Jni中的GetByteArrayElements和GetByteArrayRegion的区别和使用示例 阅读274次,点赞0次
- C++ - 判断本机文件是否存在的方式总结 阅读1682次,点赞0次
- C++11 - 使用std::thread,std::shared_future,std::promise并行化/多线程化for循环,提升处理速度 阅读490次,点赞0次
- C++ - std::map - 存储动态指针时正确释放内存 阅读2612次,点赞1次
全站随机文章推荐
- 工具网站推荐 - HDR高动态范围图像下载地址 阅读1485次,点赞0次
- 资源分享 - GLSL Essentials - Enrich your 3D scenes with the power of GLSL 英文高清PDF下载 阅读972次,点赞0次
- 资源分享 - Graphics Gems III 英文高清PDF下载 阅读1348次,点赞0次
- WordPress - 支持用户注册时使用中文名 阅读1191次,点赞0次
- WordPress - get_footer函数,加载主题底部页脚footer模板 阅读166次,点赞0次
- Windows平台录音类封装:AudioRecordWindows 阅读2859次,点赞0次
- 资源分享 - Real-Time Volume Graphics 英文高清PDF下载 阅读968次,点赞0次
- 资源分享 - Real-Time Collision Detection 英文高清PDF下载 阅读972次,点赞0次
- 资源分享 - OpenGL编程指南(原书第8版)- OpenGL红宝书高清带书签PDF下载 阅读3012次,点赞1次
- 资源分享 - Discrete and Computational Geometry 英文高清PDF下载 阅读782次,点赞0次
评论
144