0
点赞
收藏
分享

微信扫一扫

C/C++ 编程 —— 常用的回调函数实现方式(开发实现案列)

c一段旅程c 2022-03-11 阅读 45

文章目录

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;
}


在这里插入图片描述

举报

相关推荐

0 条评论