C++回调函数
///// callbackDefine.h
#ifndef __CALL_BACK_DEFINE_H__ #define __CALL_BACK_DEFINE_H__ #include <iostream> using namespace std;
// STEP1: 声明回调函数类型 typedef void (*call_back_test1)(int para1, int para2); typedef int (*call_back_test2)(int para1, int para2);
// STEP2: 定义具体回调函数 static void call_back_testA1(int para1, int para2) { cout << "call_back_test1:" << para1 << ", " << para2 << endl; } static int call_back_testA2(int para1, int para2) { cout << "call_back_test2:" << para1 << ", " << para2 << ", result:" << para1 + para2 << endl; return para1 + para2; } #endif
///// test2.h
#include <iostream> #include "callbackDefine.h"
// STEP3: 回调函数 作为 普通函数的 参数
void printTestA1(call_back_test1 call) { std::cout << "This is printTestA1" << std::endl; call(1,2); } void printTestA2(call_back_test2 call) { std::cout << "This is printTestA2" << std::endl; call(3,4); } void printTestA3(void (*call_back_testA3)(int para1, int para2)) { std::cout << "This is printTestA3" << std::endl; call_back_testA3(3,4); }
////// demo1.cpp
#include <iostream> #include "test2.h" #include "callbackDefine.h" using namespace std; int main() { printTestA1(call_back_testA1); printTestA2(call_back_testA2); // call_back_test1 call3 = [](int x, int y) { // cout << "printTestA3: x:" << x << ", y:" << y << endl; // }; auto call3 = [](int x, int y) { cout << "printTestA3: x:" << x << ", y:" << y << endl; }; // call3(4,5); printTestA3(call3); cout << "Hello world ! " << endl; return 0; }
第一步,声明回调函数的类型;
第二步,定义回调函数;
第三步,定义一个普通函数,回调函数作为该函数的一个参数
分类:
B.1.1-C/C++ 基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?