//=====================================
// f0507.cpp
// 函数指针数组
//=====================================
#include<iostream>
using namespace std;
//-------------------------------------
typedef void (*MenuFun)();
void f1(){ cout<<"good!\n"; }
void f2(){ cout<<"better!\n"; }
void f3(){ cout<<"best!\n"; }
//-------------------------------------
int main(){
MenuFun fun[]={f1,f2,f3};
for(int choice=1; choice; ){
cout<<"1-----display good\n"
<<"2-----display better\n"
<<"3-----display best\n"
<<"0-----exit\n"
<<"Enter your choice:";
cin>>choice;
switch(choice){
case 1: fun[0](); break;
case 2: fun[1](); break;
case 3: fun[2](); break;
case 0: return 0;
default: cout<<"you entered a wrong key.\n";
}
}
}//====================================
按1-3键输出不同的欢迎词,按0退出程序
仿照以上例子编一个有0-9的10个菜单,谢谢了
參考答案:#include<iostream>
using namespace std;
//-------------------------------------
typedef void (*MenuFun)();
void f1(){ cout<<"good!\n"; }
void f2(){ cout<<"better!\n"; }
void f3(){ cout<<"best!\n"; }
void f4(){ cout<<"good!4\n"; }
void f5(){ cout<<"better!5\n"; }
void f6(){ cout<<"best!6\n"; }
void f7(){ cout<<"good!7\n"; }
void f8(){ cout<<"better!8\n"; }
void f9(){ cout<<"best!9\n"; }
//-------------------------------------
int main(){
MenuFun fun[]={f1,f2,f3,f4,f5,f6,f7,f8,f9};
for(int choice=1; choice; ){
cout<<"1-----display good\n"
<<"2-----display better\n"
<<"3-----display best\n"
<<"4-----display good4\n"
<<"5-----display better5\n"
<<"6-----display best6\n"
<<"7-----display good7\n"
<<"8-----display better8\n"
<<"9-----display best9\n"
<<"0-----exit\n"
<<"Enter your choice:";
cin>>choice;
switch(choice){
case 1: fun[0](); break;
case 2: fun[1](); break;
case 3: fun[2](); break;
case 4: fun[3](); break;
case 5: fun[4](); break;
case 6: fun[5](); break;
case 7: fun[6](); break;
case 8: fun[7](); break;
case 9: fun[8](); break;
case 0: return 0;
default: cout<<"you entered a wrong key.\n";
}
}