C/C++ 编程 —— 常用的回调函数实现方式(开发实现案列)
文章目录
1、在简单函数场景中使用
#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、在类(封装)中使用
#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;
}
