C++函数指针用法

来源:《C++ Primer Plus》(第六版)(中文版)(第7章第10节函数指针)

1、代码:

#include <iostream>

//三个函数,分别返回一个数组的三个地址
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;
}

int main()
{
	using namespace std;

	double av[3] = { 12.3, 45.6, 78.9 };

	cout << "--------------------------" << endl;
	cout << "using pointers to functions" << endl;
	const double *(*p1)(const double *, int) = f1;
	auto p2 = f2;
	//or const double *(*p2)(const double *, int) = f2;

	cout << "address : value" << endl;
	cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;
	cout << p2(av, 3) << ": " << *p2(av, 3) << endl;
	cout << "--------------------------" << endl;
	cout << "using an array of pointers to functions" << endl;
	const double *(*pa[3])(const double*, int) = { f1, f2, f3 };

	cout << "address : value" << endl;
	for (int i = 0; i != 3; i++)
	{
		cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;
	}
	cout << "--------------------------" << endl;
	cout << "using a pointer to a pointer to a function" << endl;
	auto pb = pa;
	//or const double *(**pb)(const double*, int) = pa;

	cout << "address : value" << endl;
	for (int i = 0; i != 3; i++)
	{
		cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;
	}
	cout << "--------------------------" << endl;
	cout << "using pointers to an array of pointers" << endl;
	auto pc = &pa;
	//or const double *(*(*pc)[3])(const double *, int) = &pa;
	const double *pcs = (*pc)[1](av, 3);

	cout << "address : value" << endl;
	cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;
	cout << pcs << ": " << *pcs << endl;
	cout << (*(*pc)[2])(av, 3) << ": " << *(*(*pc)[2])(av, 3) << endl;
	cout << "--------------------------" << endl;

	return 0;
}
2、测试结果:

--------------------------
using pointers to functions
address : value
001DF97C: 12.3
001DF984: 45.6
--------------------------
using an array of pointers to functions
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------
using a pointer to a pointer to a function
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------
using pointers to an array of pointers
address : value
001DF97C: 12.3
001DF984: 45.6
001DF98C: 78.9
--------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值