初窥函数指针

我们通常知道的都是用指针存储一个变量的地址,这个变量具有跟指针类型相同的数据类型。除了这个功能,指针还可以指向一个函数的地址,进而来调用被指向的函数。

(1) 函数指针的声明:

 int (*pfun)(double, int);

这样就声明了一个指向参数类型是double和int的返回值类型是int的函数指针了。


函数指针通常由三部分组成:

1. 指向函数的返回类型

2. 指针名称

3. 指向函数的形参类型


(2) 如何指向一个函数:

long sum(long a, long b);

long (*pfun)(long, long) = sum;

这样就用*pfun的函数指针指向了sum这个函数。


简单实例:

#include <iostream>

using std::cout;
using std::endl;

long sum(long a, long b);
long product(long a, long b);

int main()
{
	long (*pdo_it)(long, long);
	pdo_it = product;
	cout << endl << "3*5 = " << pdo_it(3,5);

	pdo_it = sum;
	cout << endl << "3*(4*5)+6 = " << pdo_it(product(3,pdo_it(4,5)),6);
	cout << endl;

	system("pause");
	return 0;
}

long product(long a, long b)
{
	return a * b;
}

long sum(long a, long b)
{
	return a + b;
}

结果是:



(3) 函数指针作为实参:

因为“指向函数的指针”是完全合理的类型,所以函数可以拥有类型为函数指针的形参。进而,由这样的函数来调用实参指向的函数。

例子:

#include <iostream>

using std::cout;
using std::endl;

double squared(double);
double cubed(double);
double sumarray(double array[], int len, double (*pfun)(double));

int main()
{
	double array[] = {1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5};
	int len(sizeof array/sizeof array[0]);

	cout << endl << "Sum of Squared = " << sumarray(array, len, squared);
	cout << endl << "Sum of cubed = " << sumarray(array, len, cubed);
	cout << endl;

	system("pause");
	return 0;
}

double squared(double x)
{
	return x*x;
}

double cubed(double x)
{
	return x*x*x;
}

double sumarray(double array[], int len, double (*pfun)(double) )
{
	double total(0.0);
	for ( int i=0; i<len; ++i)
	{
		total += pfun(array[i]);
	}
	return total;
}
结果是:



(4)函数指针数组:

假设有三个函数:

double add(double, double);

double mul(double, double);

double div(double, double);

double (*pfun[3])(double, double) = {add, mul, div};

你可以这样调用:

pfun[1](1.5, 5.5);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值