Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

Join the forum, it's quick and easy

Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.
Evo. G Tech Team Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

函数指针 function pointer

Go down

函数指针 function pointer Empty 函数指针 function pointer

Post by too wei June 1st 2015, 00:48

先说一些关于函数的知识
函数function是很重要的一个东西,调用函数的方法通常如下
函数名(参数paramater);

例如
int add(int a,int b)          //声明(declaration)并定义(definition)一个函数。这里,add是函数名,int a和int b是参数(parameter)
{
return a+b;            //将a和b加起来并返回
}

void main()
{
int value1 = 10;  
int value2 = 33;
int sum = add(value1,value2);  //调用add函数,并返回给sum
}

结果就是,sum会等于43



函数指针(function pointer)是一个指向函数的指针,函数指针表示一个函数的入口地址
函数指针能够处理“在运行时根据数据的具体状态来选择相应的处理方式”

例如

int Add(int a,int b) {return a+b;}
int Sub(int a,int b) {return a-b;}
double AddDouble(double a,double b)  {return a+b;}

void main()
{
 int v1 = 10;
 int v2 = 32;
 int (*Math)(int,int);  //创建函数指针    //()里的类型代表着该指针可指向的函数的参数类型,
                                                      //也就是这个函数指针可以指向有着(int,int)参数类型的函数

 if(v1 <= v2) //进行比较
 {
    Math = Add;      //把指针指向Add
    printf("%d",Math(v1,v2));   //这时,Add函数就会很神奇的被调用了,也就是Add(v1,v2)被调用了
 }
  else if(v1 >= v2)
 {
    Math = Sub;     //把指针指向Sub
    printf("%d",Math(v1,v2)); //这时,Sub函数就会很神奇的被调用了,也就是Sub(v1,v2)被调用了
 }

}

在这里我们把Math函数指针指向了Add或者Sub(依if条件而定)
Add和Sub函数都有着(int,int)参数类型,所以是可行的
如果,我们尝试把Math指向AddDouble(double a,double b),编译就不会通过
因为Math无法指向(double,double)类型的函数

too wei
Sponsor
Sponsor

Posts : 31
Points : 66331
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum