通过函数指针调用函数
说明:
指针可以不但可以指向一个整形,浮点型,字符型,字符串型的变量,也可以指向相应的数组,而且还可以指向一个函数。
一个函数在编译的时候会被分配给一个入口地址。这个函数入口地址称为函数的指针。可以用一个指针变量指向函数,然后通过该指针变量调用此函数。
定义指向函数的指针变量的方法是:
int (*p) (int ,int );
int【指针变量p指向的函数的类型】 (*p)【p是指向函数的指针变量】 ( int,int )【p所指向的形参类型】;
与函数的原型进行比较
int max (int, int );
int【函数的类型】 max【函数名】 ( int,int )【函数的形参类型】;
一个例子:
一般方法的代码:
#include<iostream> using namespace std; int main(){ int max(int x,int y); int a,b,c,m; cout<<"Please input three integers:"<<endl; cin>>a>>b>>c; m=max(max(a,b),c); cout<<"Max="<<m<<endl; return 0; } int max(int x,int y){ int z; if(x>y){ z=x; } else{ z=y; } return z; }
然后,我们定义一个指针变量,指向max函数,然后通过该指针变量调用函数。
通过(*p)来调用函数
#include<iostream> using namespace std; int main(){ int max(int x,int y); int (*p) (int x,int y); p=max; int a,b,c,m; cout<<"Please input three integers:"<<endl; cin>>a>>b>>c; m=(*p)((*p)(a,b),c); cout<<"Max="<<m<<endl; return 0; } int max(int x,int y){ int z; if(x>y){ z=x; } else{ z=y; } return z; }
可以通过指针p直接调用函数
#include<iostream> using namespace std; int main(){ int max(int x,int y); int (*p) (int x,int y); p=max; int a,b,c,m; cout<<"Please input three integers:"<<endl; cin>>a>>b>>c; m=p(p(a,b),c); cout<<"Max="<<m<<endl; return 0; } int max(int x,int y){ int z; if(x>y){ z=x; } else{ z=y; } return z; }
用指向函数的指针作为函数的参数
函数指针变量最常见的用途之一是作为函数的参数,将函数名传递给其他函数的形参。这样那个就可以在调用一个函数的过程中,根据给定的不同的实参,调用不同的函数。
例如,利用该方法解决,两个函数y1=(x+1)^1; y2=(2x+3)^2 ; y3=(x^2+1)^3
分析:编写3个函数f1,f2,f3,用来求上面3个函数x+1,2x+3,x^2+1的值。
然后编写一个通用函数Squar,他有两个形参:a次方和指向函数、
程序代码:
#include<iostream> #include<math.h> using namespace std; double fun1(double n){ double r; r=n+1; return r; } double fun2(double n){ double r; r=2*n+3; return r; } double fun3(double n){ double r; r=(pow(n,2)+1); return r; } double Squar(int a, double x, double(*p)(double )){ double r,z; z=(*p)(x); r=pow(z,a); return r; } int main(){ double fun1(double n); double fun2(double n); double fun3(double n); double Squar(int a, double x, double(*p)(double )); double x; cout<<"Please input x:"; cin>>x; cout<<"(x+1)^1="; cout<<Squar(1,x,fun1)<<endl; cout<<"(2x+3)^2="; cout<<Squar(2,x,fun2)<<endl; cout<<"(x^2+1)^3="; cout<<Squar(3,x,fun3)<<endl; cout<<endl; return 0; }