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

 

第一步,声明回调函数的类型;

第二步,定义回调函数;

第三步,定义一个普通函数,回调函数作为该函数的一个参数 

 

原文链接: https://www.cnblogs.com/music-liang/p/12954499.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++回调函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/350696

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午6:28
下一篇 2023年3月2日 上午6:28

相关推荐