函数指针与回调函数

C语言中函数指针和回调函数详解

typedef int(*pfun)(int data); 定义一个指针pfun,这个指针pfun指向一个函数。这个函数以一个int为参数并返回int类型。pfun = int()(int)

菜鸟教程函数指针与回调函数

函数指针

函数指针与指针函数的区别

#include <iostream>
#include <map>

void f0() { std::cout << "err\r\n"; }
void f1() { std::cout << "f1\r\n"; }
void f2() { std::cout << "f2\r\n"; }
void f3() { std::cout << "f3\r\n"; }

typedef void(*T)();

int add(int a, int b)
{
	return a + b;
}

int main()
{
	//1.
	std::map<int, T> f = { {1,f1},{3,f2},{10,f3} };
	//等价于std::map<int, void(*)()> f = { {1,f1},{3,f2},{10,f3} };
	int n = 0;
	(f.count(n) ? f[n] : f0)();  //注意括号
	f[3]();

	//2.
	typedef int(*fun)(int, int);     //定义函数指针,参数为:(int,int)返回值为:int
	fun a = add;   //fun只是一个类型别名(类型是函数指针), fun = add;是错误的
	std::cout << a(2, 3) << '\n';

	return 0;
}

回调函数

#include <iostream>
#include <functional>

using FuncType = std::function<void(int)>;

void callBack(int i)
{
    std::cout << "回调  " << i << '\n';
}

void test(FuncType f)
{
    f(4);
    std::cout << "test\n";
}

int main()
{
    test(callBack);

    return 0;
}

如果回调函数是成员函数,可以将成员函数定义为静态的。

函数指针变量可以作为某个函数的参数来使用的,回调函数就是一个通过函数指针调用的函数。

简单讲:回调函数是由别人的函数执行时调用你实现的函数。

为什么使用回调函数

函数指针和lambda表达式

operator()

RAII机制,智能指针

posted @ 2021-03-30 20:09  滴哒哒哒  阅读(42)  评论(0编辑  收藏  举报