初窥函数指针

2014-11-24 09:18:30 · 作者: · 浏览: 0

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

(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这个函数。


简单实例:

[cpp]
#include

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) 函数指针作为实参:
因为“指向函数的指针”是完全合理的类型,所以函数可以拥有类型为函数指针的形参。进而,由这样的函数来调用实参指向的函数。

例子:

[cpp]
#include

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 {
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);