分类: C/C++
2008-04-14 18:02:18
定义一个指向函数的指针用如下的形式,以上面的test()为例:
int (*fp)(int a);//这里就定义了一个指向函数的指针
函数指针不能绝对不能指向不同类型,或者是带不同形参的函数,在定义函数指针的时候我们很容易犯如下的错误。
int *fp(int a);//这里是错误的,因为按照结合性和优先级来看就是先和()结合,然后变成了一个返回整形指针的函数了,而不是函数指针,这一点尤其需要注意!
下面我们来看一个具体的例子:
#include <iostream>
#include <string>
using namespace std;
int test(int a);
void main(int argc,char* argv[])
{
cout<
int (*fp)(int a);
fp=test;//将函数test的地址赋给函数学指针fp
cout<
cin.get();
}
int test(int a)
{
return a;
}
typedef定义可以简化函数指针的定义,在定义一个的时候感觉不出来,但定义多了就知道方便了,上面的代码改写成如下的形式:
#include <iostream>
#include <string>
using namespace std;
int test(int a);
void main(int argc,char* argv[])
{
cout<
fp fpi;//这里利用自己定义的类型名fp定义了一个fpi的函数指针!
fpi=test;
cout<
}
int test(int a)
{
return a;
}