栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

定义指向函数的指针变量的方法是:
复制代码 代码如下:
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<<"Please input three integers:"< cin>>a>>b>>c;
 m=max(max(a,b),c);
 cout<<"Max="< 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<<"Please input three integers:"< cin>>a>>b>>c;
 m=(*p)((*p)(a,b),c);
 cout<<"Max="< 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<<"Please input three integers:"< cin>>a>>b>>c;
 m=p(p(a,b),c);
 cout<<"Max="< 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<<"Please input x:";
 cin>>x;
 cout<<"(x+1)^1=";
 cout< cout<<"(2x+3)^2=";
 cout< cout<<"(x^2+1)^3="; 
 cout< cout< return 0;   
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号