函数指针:一个函数都占用一段内存单元,它们有一个起始地址,指向函数入口地址的指针称为函数指针。
一般形式:一般类型(*指针变量名)(参数表)
举例:int(*p)(int)
·注意:与返回指针的函数之间的区别
int(*p)(int)是指针:指向一个函数入口地址
int *p(int)是函数:函数的返回值是一个int类型指针
指针函数:
int *p(int)是函数:函数的返回值是一个int类型指针
下面请看实例代码:
#include <iostream>
using namespace std;
int MaxValue(int x,int y)
{
return (x>y)?x:y;
}
int MinValue(int x,int y)
{
return (x<y)?x:y;
}
int add(int x,int y)
{
return x+y;
}
bool processNum(int x,int y,int (*p)(int a,int b))
{
cout << p(x,y)<<endl;
return true;
}
int main(int argc, const char * argv[])
{
int x = 10,y = 20;
cout <<"what is MaxValue:"<<processNum(x,y,MaxValue)<<endl;
cout <<"what is MinValue:"<<processNum(x,y,MinValue)<<endl;
cout <<"what is addValue:"<<processNum(x,y,add)<<endl;
return 0;
}
打印结果:
what is MaxValue:20
1
what is MinValue:10
1
what is addValue:30
1
注意:main函数中打印出来的结果其实只有1,那为什么我们实现了对应的函数指针指向的函数体所实现的功能呢?因为proceesNum中我们实现这个函数体中返回了具体的函数实现打印值,而这也是回调函数的一种实现,我们不去控制具体函数体的调用,在函数中去调对应的函数。