学习C++ Primer Plus 深入探讨函数指针示例记录

#include<iostream>
#include<string>
using namespace std;
const double * f1(const double ar[], int n);//f1返回ar,*ar=1112.3
const double * f2(const double [], int);//f2返回ar+1,*(ar+1)=1542.6
const double * f3(const double *, int);//f3返回ar+2,*(ar+2)=2227.9;  f1,f2,f3函数类型相同
int main()
{
	double av[3] = { 1112.3,1542.6,2227.9 };
	const double *(*p1)(const double *, int) = f1;//定义函数指针p1,指向指针函数f1
	auto p2 = f2;//自识别关键字auto ,p2=f2 是指针函数
	cout << "Using pointers to functions:\n";
	cout << " Address Value\n";
	//(*p1)(av, 3):用函数指针p1调用f1,返回ar的地址;*(*p1)(av, 3) 取值
	cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;
	//p2(av, 3)相当于f2(av,3),返回ar+1的地址;*p2(av, 3)取值
	cout << p2(av, 3) << ": " << *p2(av, 3) << endl;
	//定义函数指针数组
	const double *(*pa[3])(const double *, int) = { f1,f2,f3 };
	//数组名是指向数组的第一个元素的指针,所以pa是指向函数指针的指针,即*pa=pa[0]=f1,pa[1]=*(pa+1)=f2,...
	auto pb = pa;
	cout << "\nUsing an array of pointers to functions:\n";
	cout << " Address Value\n";
	for (int i = 0;i < 3;i++)
	{
		cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;
		//cout << (*(pa + i))(av,3) << ": " << *(*(pa + i))(av, 3) << endl;
	}
	cout << "\nUsing a pointer to a pointer to a function:\n";
	cout << " Address Value\n";
	for (int i = 0;i < 3;i++)
	{
		cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;
	}
	cout << "\nUsing pointers to an array of pointers:\n";
	cout << " Address Value\n";
	auto pc = &pa;
	cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;

	const double *(*(*pd)[3])(const double *, int) = &pa;//*pd=pa;
	const double *pdb = (*pd)[1](av, 3);//pdb=f2(av,3)
	cout << pdb << ": " << *pdb << endl;
	//(*(*pd)[2])(av, 3)->(*pa[2])(av,3)->(*f3)(av,3)->ar+2 ; 函数名就是该函数的地址
	cout << (*(*pd)[2])(av, 3) << ": " << *(*(*pd)[2])(av, 3) << endl;
	cin.get();
	return 0;
}
const double * f1(const double *ar, int n)
{
	return ar;
}
const double * f2(const double ar[], int n)
{
	return ar + 1;
}
const double * f3(const double ar[], int n)
{
	return ar + 2;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值