第十二週專案3—摩托車繼承自行車和機動車
阿新 • • 發佈:2019-01-24
/* *程式的版權和版本宣告部分: *Copyright(c)2014,煙臺大學計算機學院學生 *All rights reserved. *檔名稱: *作者:初瑞 *完成日期:2014 年 5 月 13 日 *版本號:v1.0 *對任務及求解方法的描述部分: *輸入描述:無 *問題描述:在下面一段類的定義中,自行車類的虛基類為車輛類,機動車類的虛基類也為車輛類, 摩托車類的基類為自行車類和機動車類,類之間均為公有繼承。 (1)根據上面各類間關係的描述,補全下面程式段中空缺的程式碼; (2)實現程式中宣告的成員函式,注意相應操作中的動作發生的條件不能滿足時應給出提示。 (3)執行程式,享受開摩托的過程。 (4)在報告中,請用自己的話寫清楚使用虛基類解決什麼問題? *程式輸出: *問題分析: *演算法設計: */ #include <iostream> #include<conio.h> #include <windows.h> using namespace std; enum vehicleStaus {rest, running}; //車輛狀態:泊車、行進 class vehicle //車輛類 { protected: int maxSpeed; //最大車速 int currentSpeed; //當前速度 int weight; //車重 vehicleStaus status; //rest-泊車狀態;running-行進狀態 public: vehicle(int maxS, int w); //建構函式,初始時,當前速度總為0且處在停車狀態 void start(); //由rest狀態到running, 初速為1 void stop(); //由running狀態到rest, 當前速度小於5時,才允許停車 void speed_up(); //加速,呼叫1次,速度加1 void slow_down(); //減速,呼叫1次,速度減1,速度為0時,停車 }; vehicle::vehicle(int maxS,int w):maxSpeed(maxS),weight(w),currentSpeed(0),status(rest){} void vehicle::start() { if(status==0) { status=running; currentSpeed=1; } else cout<<"車輛已經執行!"<<endl; } void vehicle::stop() { if(status==1) { if(currentSpeed>5) cout<<"車速太快,請先減速!"<<endl; else { status=rest; currentSpeed=0; } } else cout<<"車輛未啟動!"<<endl; } void vehicle::speed_up() { if(status==running) { if(currentSpeed<maxSpeed) currentSpeed++; else cout<<"已達最大速度!"<<endl; } else cout<<"車輛未啟動!"<<endl; } void vehicle::slow_down() { if(status==running) { if(currentSpeed>0) currentSpeed--; if(currentSpeed==0) { cout<<"已停車!"<<endl; status=rest; } } else cout<<"車輛未啟動!"<<endl; } class bicycle:virtual public vehicle//(1)自行車類的虛基類為車輛類 { protected: double height; //車高 public: bicycle(int maxS=10, int w=50, int h=0.7); //定義建構函式 }; bicycle::bicycle(int maxS, int w, int h) :vehicle(maxS,w),height(h){} class motorcar:virtual public vehicle//(2)機動車類的虛基類也為車輛類 { protected: int seatNum; //座位數 int passengerNum; //乘客人數 public: motorcar(int maxS=150, int w=1500, int s=5, int p=1); //定義建構函式 void addPassenger(int p=1); //增加搭載的乘客,超員要拒載,有人下車時,p為負數。當然車上乘客至少有1個(司機)。 //只有車停穩後才能上下客。 }; motorcar::motorcar(int maxS, int w, int s, int p) :vehicle(maxS,w),seatNum(s),passengerNum(p){} void motorcar::addPassenger(int p) { if(status==running) cout<<"為了保證安全,請先停車!"<<endl; else { passengerNum+=p; if(passengerNum>seatNum) cout<<"涉嫌超員!"<<endl; if(passengerNum<1) { passengerNum=1; cout<<"司機不要離開崗位!"<<endl; } } } class motorcycle:public bicycle,public motorcar //(3)摩托車類的基類為自行車類和機動車類 { public: motorcycle(int maxS=90, int w=100, int s=3, int p=1, int h=0.7);//定義建構函式 void show(); //顯示摩托車的執行狀態 }; motorcycle::motorcycle(int maxS, int w, int s, int p, int h) :vehicle(maxS,w),bicycle(maxS,w,h),motorcar(maxS,w,s,p){} void motorcycle::show() { cout<<"狀態:"<<endl; if(status==rest) cout<<"泊車\t"; else cout<<"執行\t"; cout<<"車速:"<<currentSpeed<<" / "<<maxSpeed<<"\t當前成員:"<<passengerNum<<" / "<<seatNum<<endl; } int main( ) {
運算結果: