php 调用成员函数指针,如何通过函数指针调用函数(实现代码)

说明:指针可以不但可以指向一个整形,浮点型,字符型,字符串型的变量,也可以指向相应的数组,而且还可以指向一个函数。

一个函数在编译的时候会被分配给一个入口地址。这个函数入口地址称为函数的指针。可以用一个指针变量指向函数,然后通过该指针变量调用此函数。

定义指向函数的指针变量的方法是:

int (*p) (int ,int );

int【指针变量p指向的函数的类型】 (*p)【p是指向函数的指针变量】 ( int,int )【p所指向的形参类型】;

与函数的原型进行比较

int max  (int, int );

int【函数的类型】 max【函数名】 ( int,int )【函数的形参类型】;

一个例子:一般方法的代码:

#include

using namespace std;

int main(){

int max(int x,int y);

int a,b,c,m;

cout<

cin>>a>>b>>c;

m=max(max(a,b),c);

cout<

return 0;

}

int max(int x,int y){

int z;

if(x>y){

z=x;

} else{

z=y;

}

return z;

}

然后,我们定义一个指针变量,指向max函数,然后通过该指针变量调用函数。

通过(*p)来调用函数

#include

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<

cin>>a>>b>>c;

m=(*p)((*p)(a,b),c);

cout<

return 0;

}

int max(int x,int y){

int z;

if(x>y){

z=x;

} else{

z=y;

}

return z;

}

可以通过指针p直接调用函数

#include

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<

cin>>a>>b>>c;

m=p(p(a,b),c);

cout<

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

#include

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<

cin>>x;

cout<

cout<

cout<

cout<

cout<

cout<

cout<

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值