什么是回调函数?
- 定义:可以作为参数被调用的函数叫做回调函数。
- 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;
}
回调函数的应用场景
- 执行事件驱动的任务
- 让需要调用callback function的函数有更灵活的实现