已经写了前面的一篇,其实已经不用在这里说明了,但是既然我写了,不发一下我觉得也不爽,因此就再浪费点时间吧
例题: 定义一个Currency类,派生出人民币类、日元类、港币类。三个派生类的输出格式各不相同(display()成员函数的实现不同)。编制应用程序,分别输出这三个类所创建的对象的币值输出。 程序:
Currency.h #include<iostream> #include<string> using namespace std; class Currency{ protected: string name; double number; public: Currency(string n,double nu):name(n),number(nu){}; virtual void display()=0; }; class RMB:public Currency{ public: RMB(double nu):Currency("人民币",nu){}; void display(); }; class yen:public Currency{ public: yen(double nu):Currency("日元",nu){}; void display(); }; class HKD:public Currency{ public: HKD(double nu):Currency("港币",nu){}; void display(); }; void f(Currency& s);
function.cpp #include"Currency.h" #include<iostream> using namespace std; void RMB::display(){ cout<<"币种:"<<name<<'/t'<<"¥ "<<number<<"元"<<endl; } void yen::display(){ cout<<"币种:"<<name<<'/t'<<"¥ "<<number<<"円"<<endl; } void HKD::display(){ cout<<"币种:"<<name<<'/t'<<"HKD "<<number<<"港币"<<endl; } void f(Currency& s){ s.display(); }
Currency.cpp #include"Currency.h" #include<iostream> #include<string> using namespace std; void main(){ int choice; double a,b,c; while(1){ cout<<"***菜单***"<<endl; cout<<"1、人民币"<<endl; cout<<"2、日元"<<endl; cout<<"3、港币"<<endl; cout<<"4、退出"<<endl; cout<<"请选择所需币种~~~"<<endl; cin>>choice; switch(choice){ case 1:{ cout<<"请输入货币数量:"<<endl; cin>>a; RMB m(a);f(m);break; } case 2:{ cout<<"请输入货币数量:"<<endl; cin>>b; yen n(b);f(n);break; } case 3:{ cout<<"请输入货币数量:"<<endl; cin>>c; HKD o(c);f(o);break; } case 4:exit(0); default:cout<<"对不起,您的输入有误!";exit(0); } } } 解析:这个程序比较短了,不过在这个程序里倒是让我认识了一个新的只是,就是日元单位,还有要注意的是在这里switch里面case中的一些东西的生存域,我写的时候就没注意这个问题,编译就出错了,后来才改过来的,因此编程真是一项细致活啊
漫漫编程路——C++篇(八)——关于虚函数和多态性 (二)
最新推荐文章于 2024-04-26 10:21:53 发布