回调函数(callback function)

发布时间 2023-05-06 12:40:58作者: 无形深空

是什么

回调函数是一种特殊的函数,它不是在程序中直接调用的,而是由程序在特定事件发生时进行调用的。回调函数通常作为参数传递给其他函数,而这些函数在执行时会将回调函数作为其内部的一部分来调用。
image

为什么

  • 解耦.
    • 回调函数的好处在于它们可以让程序更加模块化和可扩展。

怎么样

例:

#include<iostream>
using namespace std;

int Callback_1(int x) // Callback Function 1
{
    cout<<"hello, this is Callback_1: x = "<<x<<endl;
    return 0;
}

int Callback_2(int x) // Callback Function 2
{
    cout<<"hello this is Callback_2: x = "<<x<<endl;
    return 0;
}

int Handle(int y, int (*Callback)(int)) //可以将函数当作参数传递, 增加一个参数y来灵活操作
{
    cout<<"entering Handle Function."<<endl;
    Callback(y);                        //调用回调函数
    cout<<"entering Handle Function."<<endl<<endl;
    return 0;
}

int main(int argc, char const *argv[]) {
    int a = 2;
    int b = 4;
    Handle(a, Callback_1);              //将函数名作为参数传递
    Handle(b, Callback_2);
    return 0;
}

image

例:
定义了一个函数指针类型

typedef REAL(*GetVertexParamOnEdge)(void*, int, int);