|
/* menu.c: Illustrates an array of function ptrs*/
/* You must provide definitions for these:*/
/*函数也具有地址,且函数的地址是存储其机器语言代码的内存的地址的开始地址
将函数地址传递给某个函数的步骤:
一.获取函数的地址,函数名是指向该函数的指针,要将函数作为参数进行传递,必须传递函数名
eg:
process(think);//使得process函数在其内部调用think(),函数
throught(think());//thought函数首先调用think()函数,然后将think()的返回值传递给th..函数
二.声明函数指针,需声明指向函数的指针,且声明时像声明函数一样指定函数的返回类型和函数的参数列表,声明时,函数指针一般要与待指向的函数类型相同:
eg:double pam(int);double (*pf)(int);//必须用括号括起(*pf),否则意为返回类型为double *
把函数地址作为参数 eg:
void estimate(int lines,double (*pf)(int));
让estimate函数使用pam()函数,需将pam()地址传递给它 eg:estimate(50,pam);
三.使用函数指针调用函数(当pf=pam)
1.pam(5);//原函数地址
2.pf(5);
3.(*pf)(5);
注:从用法来说,pf与(*pf)等价
*/
#include<iostream>
double *f1(double *,int);
double *f2(double *,int);
double *f3(double *,int);
using namespace std;
int main()
{
int choice;//声明函数指针数组
double av[]={1.1,2.2,3.3};
double *(*farray[])(double *,int) =
{//前提:三个函数的返回类型和参数列表相同
f1,f2,f3
};
auto pd=&farry;
//auto pd=&farray;pc为指向整个函数指针数组的指针
//或:double *(*(*pd)[])(double *,int)=&farry;
for (;;)
{
if(choice >= 1 && choice <= 3)
{
/* Process request: */
farray[choice-1](av,3);
double ac=*farray[choice-1](av,3);
//列出的4种情况:
(*pd)[choice-1](av,3);
double ar=*(*pd)[choice-1](av,3);
//或者是用(*pf,即指向函数的指针的值):
(*(*pd)[choice-1])(av,3);
double am=*(*(*pd)[choice-1])(av,3);
}
else if (choice == 4)
break;
}
return 0;
} |
上一篇: 字符串查找下一篇: 硬编码复习笔记
|