您的位置:首页 > 编程语言 > C语言/C++

C语言指向函数的指针

2015-06-10 10:20 309 查看
函数是由指令序列构成的,其代码存储在连成一片的内存单元中,这些代码中的第一个代码所在的内存地址称为首地址。

首地址是函数的入口地址。主函数在调用子函数时,就是让程序转移到函数的入口地址去执行。

#include <iostream>
using namespace std;
int sum = 0;
int m = 0;
void food1(){
cout<<"drink"<<endl;
sum = sum+5;
m++;
}
void food2(){
cout<<"food"<<endl;
sum = sum+5;
m++;
}
int main(){
typedef void (*MenuFood)();//定义一个指向函数的指针类型,名为MenuFood
MenuFood p[] ={food1,food2};
cout<<"1.drink"<<endl;
cout<<"2.food"<<endl;
cout<<"0.exit"<<endl;
int choice;
do{
cin>>choice;
switch (choice)
{
case 1:
p[0]();
break;
case 2:
p[1]();
break;
case 0:
break;
default:
cout<<"Please input right number";
}
}while (choice!=0);
cout<<"sum="<<sum<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: