实验目的
1.理解重载运算符的意义。
2.掌握使用成员函数、友员函数重载运算符的特点。
3.掌握重载运算符函数的调用方法。
4.掌握动态联编的概念。
5.掌握虚函数和纯虚函数的使用方法。
实验内容
一个小型快捷酒店有5个房间,其中3个标准间,2个大床间,可在柜台办理入住或退房。
标准间180元/天,大床间120元/天,押金都是100元。
请利用类的多态特性实现该系统。
代码
仅供交流学习,请勿抄袭
上交时间截至了再发出来没什么问题。
主要部分就40行 感觉还是挺精简地完成了这个demo
#include<iostream>
using namespace std;
class room{
public:
virtual void order() = 0;
virtual void cancel() = 0;
};
class stdRoom:public room{
int ordered = 0;
friend ostream& operator<<(ostream& out, stdRoom& s);
public:
void order()final{
if(ordered<3) ordered++;
else cout<<"full!"<<endl;
};
void cancel()final{
if(ordered>0) ordered--;
else cout<<"null!"<<endl;
};
};
class bigRoom:public room{
int ordered = 0;
friend ostream& operator<<(ostream& out, bigRoom& b);
public:
void order()final{
if(ordered<2) ordered++;
else cout<<"full!"<<endl;
};
void cancel()final{
if(ordered>0) ordered--;
else cout<<"null!"<<endl;
};
};
ostream& operator<<(ostream& out, stdRoom& s){
out << "标准间预定了:" << s.ordered << endl;
return out;
};
ostream& operator<<(ostream& out, bigRoom& b){
out << "大床间预定了:" << b.ordered << endl;
return out;
};
room *r;
stdRoom s;
bigRoom b;
void hint(){
cout<<"标准间180元/天,大床间120元/天,押金都是100元。"<<endl;
cout<<"共有3个标准间,2个大床间"<<endl;
cout<<"标准间已经预定:"<<s<<endl<<"大床间已经预定:"<<b<<endl;
}
void hp(){
cout << "| 1、入住标准间 |" << endl;
cout << "| 2、入住大床间 |" << endl;
cout << "| 3、退订标准间 |" << endl;
cout << "| 4、退订大床间 |" << endl;
cout << "| 5、查看房间预定 |" << endl;
cout << "| 0、退出 |" << endl;
};
int main(){
int ch;
hint();
hp();
while(cin>>ch){
switch (ch)
{
case 1:
r=&s;
r->order();
break;
case 2:
r=&b;
r->order();
break;
case 3:
r=&s;
r->cancel();
break;
case 4:
r=&b;
r->cancel();
break;
case 5:
hint();
break;
case 0:
return 0;
default:
break;
}
}
system("pause");
return 0;
}