首页 > 编程语言 > 详细

C++回调函数

时间:2020-05-25 10:08:35      阅读:49      评论:0      收藏:0      [点我收藏+]

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

 

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

第二步,定义回调函数;

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

 

C++回调函数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!