ZSTU c++作業——類的多態性的實現

實驗目的

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章