函数存放在代码的内存区域内,函数名代表了函数的地址,如:int fun(int a);fun就是函数在内存中的地址。
1.定义一个指向函数的指针
以int fun(int a)为例:
int(*fp)(int a);//定义了一个指向函数的指针.
注意与int *fp(int a)的区别,
int *fp(int a);//声明了一个返回int 型指针的函数.
#include<iostream>
#include<windows.h>
using namespace std;
int fun(int a)
{
return a;
}
int main()
{
cout<<fun<<endl;
int(*fp)(int a);
fp=fun;
cout<<fp(5)<<endl;
cout<<(*fp)(10)<<endl;
Sleep(1000);
return 0;
}
2.用typedef定义简化函数指针的定义
typedef int(*fp)(int a);
fp fp1=fun;
cout<<fp1(5)<<endl;
cout<<(*fp1)(10)<<endl;</strong></span>
3.函数指针作为参数传递给函数。
#include<iostream>
#include<windows.h>
using namespace std;
int fun(int a)
{
return a;
}
int Test(int(*fp)(int),int b)
{
return fp(1)+b;
}
int main()
{
typedef int(*fp)(int a);
fp fpi=fun;
cout<<Test(fpi,2)<<endl;
Sleep(1000);
return 0;
}
4.构成指向函数的指针数组
几个名字不同的函数,只要返回类型和参数个数,参数类型一致,就是同一类函数指针。
#include<iostream>
#include<windows.h>
using namespace std;
int fun1(int a)
{
return a;
}
int fun2(int a)
{
return a+1;
}
int fun3(int a)
{
return a+2;
}
int main()
{
typedef int(*fp)(int a);
fp b[]={fun1,fun2,fun3};
cout<<b[0](1);
return 0;
}
1.定义一个指向函数的指针
以int fun(int a)为例:
int(*fp)(int a);//定义了一个指向函数的指针.
注意与int *fp(int a)的区别,
int *fp(int a);//声明了一个返回int 型指针的函数.
#include<iostream>
#include<windows.h>
using namespace std;
int fun(int a)
{
return a;
}
int main()
{
cout<<fun<<endl;
int(*fp)(int a);
fp=fun;
cout<<fp(5)<<endl;
cout<<(*fp)(10)<<endl;
Sleep(1000);
return 0;
}
2.用typedef定义简化函数指针的定义
typedef int(*fp)(int a);
fp fp1=fun;
cout<<fp1(5)<<endl;
cout<<(*fp1)(10)<<endl;</strong></span>
3.函数指针作为参数传递给函数。
#include<iostream>
#include<windows.h>
using namespace std;
int fun(int a)
{
return a;
}
int Test(int(*fp)(int),int b)
{
return fp(1)+b;
}
int main()
{
typedef int(*fp)(int a);
fp fpi=fun;
cout<<Test(fpi,2)<<endl;
Sleep(1000);
return 0;
}
4.构成指向函数的指针数组
几个名字不同的函数,只要返回类型和参数个数,参数类型一致,就是同一类函数指针。
#include<iostream>
#include<windows.h>
using namespace std;
int fun1(int a)
{
return a;
}
int fun2(int a)
{
return a+1;
}
int fun3(int a)
{
return a+2;
}
int main()
{
typedef int(*fp)(int a);
fp b[]={fun1,fun2,fun3};
cout<<b[0](1);
return 0;
}