终于搞懂了回调函数

什么是回调函数?

  • 定义:可以作为参数被调用的函数叫做回调函数。
  • call-back function的核心是call,也就是说,核心在于“调”,而不在于“回”。(我以前经常被这个“回”字弄得晕头转向。)

回调函数的使用方法

下面的代码是我看这个视频https://www.youtube.com/watch?v=sxTFSDAZM8s,然后自己码的C++版。亲测可用。

#include <iostream>

using namespace std;

void A() {
	cout << "hello world" << endl;
}


void B(void (*ptr) ()) { // the param is a function pointer that points to void param and void return value function
	ptr();
}

//写一个降序冒泡排序,再写一个升序冒泡排序,代码重复率太高
//为了复用冒泡排序,我们可以给冒泡排序加一个参数
void bubbleSort(int *a, int n,int (*compare)(int,int)) {
	int i, j, temp;
	for (i = 0; i < n; i++)
		for (j = 0; j < n - 1; j++) {
			if (compare(a[j], a[j+1])< 0) { //by change > 0 or < 0 to choose increasing or decreasing
				temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
		}
}

int comp(int a, int b) {
	if (a > b) return 1;
	else return - 1;
}

int main() {
	//part1
	void(*ptr)();
	ptr = A;
	B(ptr);

	//part2
	int i,A[] = {3,1,2,6,5,4};
	bubbleSort(A, 6,comp);
	for (i = 0; i < 6; i++) cout << A[i] << " " << endl;

	return 0;
}

回调函数的应用场景

  1. 执行事件驱动的任务
  2. 让需要调用callback function的函数有更灵活的实现
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值