一、定义
定义
二、例子
#include "pch.h"
#include <iostream>
typedef int (callBack)(int, int);
int CallSum(callBack *p, int x, int y) {
return (*p)(x, y);
}
int Sum(int x_, int y_) {
return x_ + y_;
}
int main() {
int kSum=CallSum(Sum, 4,9);
std::cout << kSum << std::endl;
return 0;
}
运行结果:
13
三、实际用法
algorithm标准库中的sort排序。
#include "pch.h"
#include <iostream>
#include <algorithm>
bool callcmp(int a, int b) {
return a > b;
}
int main(void) {
int a[9] = { 0,1,3,5,2,8,7,6,9 };
std::sort(a, a + 9, callcmp);
for (size_t i : a)
{
std::cout << i << std::endl;
}
return 0;
}
运行结果:
9
8
7
6
5
3
2
1
0
本文详细解析了C++中回调函数的概念及应用,通过实例展示了如何使用回调函数进行求和运算,并深入探讨了algorithm标准库中的sort排序功能,通过自定义比较函数实现数组逆序排列。

1523

被折叠的 条评论
为什么被折叠?



