文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。
笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888
1、在简单函数场景中使用
// ConsoleApplication.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
#include <string.h>
using namespace std;
using callback = std::function<void(std::string &strBuf, int &iLen)>; //定义回调函数格式
void callBack_test(std::string &strBuf, int &iLen) // 定义回调函数
{
strBuf = "Return text !";
iLen = 100;
}
int main(int argc, char *argv[])
{
std::string strBuf = "";
int iLen = 0;
callback Fun_cb = callBack_test; // 设置回调函数
if (nullptr != Fun_cb) // 判断是否为空
{
Fun_cb(strBuf, iLen); // 触发回调函数
std::cout << strBuf << " - " << iLen << std::endl; // 打印输出
}
system("pause");
return 0;
}
2、在类(封装)中使用
// ConsoleApplication.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
#include <string.h>
using namespace std;
using callback = std::function<void(std::string &strBuf, int &iLen)>; //定义回调函数格式
class MyClass // 封装类
{
public:
MyClass() {}
~MyClass() {}
bool set_cb_fun(callback cb_fun) //设置回调函数
{
bool bRet = false;
if (nullptr != cb_fun) // 合法性判断
{
m_cb_fun = cb_fun;
bRet = true;
}
return bRet;
}
void send(std::string str) // 触发回调函数
{
str.append(" callback");
int iLen = static_cast<int>(str.length());
m_cb_fun(str, iLen);
}
private:
callback m_cb_fun;
};
void callBack_printf(std::string &strBuf, int &iLen) // 定义回调函数
{
std::cout << "myClass : " << strBuf << " - " << iLen << std::endl;
}
int main(int argc, char *argv[])
{
MyClass my;
if (my.set_cb_fun(callBack_printf)) // 设置回调函数
{
std::string strBuf = "hello";
my.send(strBuf); // 触发回调函数
}
system("pause");
return 0;
}
3、在类(成员函数)中的使用
// ConsoleApplication.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
#include <string.h>
using namespace std;
using CallBack = std::function<void(std::uint32_t const& value)>;
class MyClass1
{
public:
MyClass1()
{
callback_ = nullptr;
is_start_ = false;
count_ = 0;
}
~MyClass1()
{
is_start_ = false;
}
void setCallBack(CallBack callback) {
if (callback != nullptr)
{
callback_ = callback;
is_start_ = true;
printf("MyClass1 set callback is suc.\n");
}
else
{
printf("MyClass1 callback is null.\n");
}
}
void start()
{
while (is_start_)
{
callback_(count_);
printf("MyClass1 current count is %d \n", count_);
++ count_;
sleep(1);
}
}
public:
CallBack callback_;
bool is_start_;
std::uint32_t count_;
};
class MyClass2
{
public:
MyClass2() {}
~MyClass2() {}
/// @brief 定义回调函数
static void printfCallback(std::uint32_t const& value)
{
printf("MyClass2 current count is %d \n", value);
}
/// @brief 设置回调函数
void SetCallback()
{
obj1.setCallBack(printfCallback);
}
// 启动 MyClass1 的回调函数
void Run()
{
obj1.start();
}
public:
MyClass1 obj1;
};
int main(int argc, char *argv[]) {
std::shared_ptr<MyClass2> obj2 = std::make_shared<MyClass2>();
obj2->SetCallback();
obj2->Run();
system("pause");
return 0;
}