由于函数在内存中也占据存储空间的,也是有起始地址的,因此也可以用指针指向函数起始地址,即可以使用指针调用对应函数。
.函数指针的定义
格式:存储类型 数据类型 (*函数指针名)()
注1:将*和函数名的连起的括号不可少,否则就会成为指向函数的指针(即返回一个指针类型的函数)
注2:函数类型必须匹配要调用的函数类型,函数形参表要匹配调用的函数形参表。如:
int max(int a,int b);
int min(int a,int b);
int (*fun)(int a,int b);
含义
函数指针指向的是程序代码存储区
.函数指针的典型用途——实现函数回调
.通过函数指针调用的函数
例如将函数的指针作为传递给一个函数,使得在处理相似事件的时候可以灵活使用不同的方法。
.调用者不关心谁是被掉用者
需知道存在一个具有特定原型和限制条件的被调用函数
例:
#include <iostream>
using namespace std;
int compute(int a,int b,int (*func)(int,int))
{
return func(a, b);
}
int max(int a,int b)
{
return ((a > b) ? a : b);
}
int min(int a, int b)
{
return ((a < b) ? a : b);
}
int sum(int a, int b)
{
return a+b;
}
int main()
{
cout<<compute(1, 10, max)<<endl;
cout << compute(1, 10, min) << endl;
cout << compute(1, 10, sum) << endl;
}
//结果为10 1 11