C++ 回调函数之函数指针

零、名词解释

  • 回调函数:回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。---百度百科
  • 函数指针:本质上是一个指针,指向一个函数。

一、函数指针

定义: type (*pFun) (typeA, typeB);

        指向的函数的返回类型  (* 函数指针名称)  (指向的函数的形参A类型, 指向的函数的形参B类型)

例子:

// 定义函数
int add(int &a, int &b) {
    return a+b;
}

// 定义函数指针
int (*pFun) (int, int);

// 函数指针赋值
pFun = add;

二、函数指针实现回调函数

  各种事件响应其实底层都是用的是回调函数的方式

#include <iostream>

using namespace std;

// 回调函数
void onLargerThan100(int res) {
    if(res>100){
        cout<<"res larger than 100"<<endl;
    } else {
        cout<<"res smaller than 100"<<endl;
    }
}

// 主调函数
void SayHello(void (*callback) (int), int a, int b) {
    int sum = a+b;
    // 结果传入回调
    callback(sum);
}

int main()
{
    void (*callback) (int);

    callback = onLargerThan100;

    SayHello(callback , 1, 2);

    SayHello(callback , 100, 2);

    return 0;
}


结果:

 

三、结束

      拜拜!

猜你喜欢

转载自blog.csdn.net/qianlixiaomage/article/details/107301320