C++学习笔记系列2-48——回调函数

回调函数

定义:将一个函数 A 的函数指针作为另一个函数 B 的参数使用,当调用函数 B 时,通过函数指针间接调用函数 A。简单理解就是使用函数指针作为参数。

复制代码
#include <iostream>
using namespace std;
// test1 将作为函数指针传入 test2函数中
void test1()
{
    cout << "test1函数" << endl;
}
// 注意这里的参数
void test2(void(*func)())
{
    cout << &test1 << endl; // 我们取函数地址
    cout << *func << endl;  // 我们取函数指针中存储的地址
    test1();// 普通调用
    func(); // 函数指针方式调用
    cout << "test2函数" << endl;
}

int main()
{
    void (*func)() = test1;
    test2(test1);
    // test2函数的参数列表中填入函数指针"func",即:test2(func),也可以输出
}

输出:0xff7869

0xff7869

test1函数

test1函数

test2函数

回调函数可以用于不同条件下输出不同结果