c++ functional之函数指针

函数对象
匿名函数
回调函数
function和bind

#include <iostream>
using namespace std;
using AVE_PTR = double(*)(const double*, const int); // 给函数指针取别名
typedef double(*AGE)(const double*, const int);
// using 和typedef 都给了double(*)(const double*, const int); 都是一样的但是typedef不能用于函数模板的指针类型
double average(const double* arr, const int n) {
	auto ave = arr[0];
	for (auto i = 1; i != n; i++)
		ave += arr[i];
	ave /= n;
	return ave;
}

int main() {
	double(*pf)(const double*, const int) = &average; //pf 就是函数指针指向函数的 类型(*pf) (参数) = 函数名 也可以加& 都是一样的
	double a[]{ 1,2,3,4,5 };
	AVE_PTR p = average;
	AGE p1 = average;
	cout << pf(a, 5) << '\t' << average(a, 5)<<"\t"<<p(a,5)<< "\t" << p1(a, 5) << endl; // 可以通过函数指针去调用这个函数 和 调用函数一样的
	while (true);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值