我寫了一個程序,允許用戶取出和返回車輛。例如,用戶決定將汽車開出供個人使用,剩餘的車輛數量將從2減少到1.問題是,無論何時創建新物體,綜合車輛類別中的車輛數量將會總是默認2,當你檢出一輛車時,它只會減少創建該對象的車輛數量。我不擅長解釋,所以也許這會有所幫助。如何使用多態性將複合對象全局化爲派生類?
int main(){
int a = 0;
int vn;
int counter = 0;
VMS *tracking[20];
while (a != 6){
cout << "(1) Company (2) Personal (3) Carpool (4) Cargo (5) Return a vehicle (6) Exit" << endl << "Select the appropriate application: ";
cin >> a;
switch (a){
case 1: tracking[counter] = new company(); cout << "YOU ARE USER #" << counter << " PLEASE REMEMBER YOUR USER NUMBER"; counter++; break;
case 2: tracking[counter] = new personal(); cout << "YOU ARE USER #" << counter << " PLEASE REMEMBER YOUR USER NUMBER"; counter++; break;
case 3: tracking[counter] = new carpool(); cout << "YOU ARE USER #" << counter << " PLEASE REMEMBER YOUR USER NUMBER"; counter++; break;
case 4: tracking[counter] = new cargo(); cout << "YOU ARE USER #" << counter << " PLEASE REMEMBER YOUR USER NUMBER"; counter++; break;
case 5: cout << "Please enter your User #: "; cin >> vn; tracking[vn]->returned(); break;
case 6: exit(1); break;//exit
}
所以每次1 - 4已經選擇了新的對象將被創建並每次會有複合車輛類,默認2的一個新實例,以剩餘的車輛的數量。我希望做的是以某種方式使所有創建的對象在全球級車輛減少量的車輛減少,以便當車輛的數量= 0時,提示將顯示這樣的。還有什麼辦法可以通過在基類中仍然有一個車輛組合來完成這個任務嗎? 我不太確定包含哪些代碼會有所幫助,所以我認爲這些可能會有所幫助。
基類:
class VMS{
public:
VMS(){}
virtual void set();
virtual void print();
virtual void returned();
virtual void setV();
private:
string purpose;
string dName;
int emplidNum;
string date;
string Time;
string rtime;
vehicle vehicle;//Composition of vehicle class
};
#endif
車輛類別:(組成)
class vehicle{
public:
vehicle() { sedan = 2, pickup = 2, minivan = 2; }
bool empty1(){
if (sedan == 0){
cout << "All Vehicles of this type are in use, please select a different vehicle" << endl;
return true;
}
else
return false;
}
bool empty2(){
if (pickup == 0){
cout << "All Vehicles of this type are in use, please select a different vehicle" << endl;
return true;
}
else
return false;
}
bool empty3(){
if (minivan == 0){
cout << "All Vehicles of this type are in use, please select a different vehicle" << endl;
return true;
}
else
return false;
}
//the vehicle objects
int sedan;
int pickup;
int minivan;
};
#endif
很抱歉的柱的長度。任何幫助,將不勝感激。
這個答案是正確的,但在OP的設計中似乎也存在缺陷。讓'Garage'類充當'車輛'的分銷商並且記錄每輛'車輛'有多少可用的情況會更有意義。 – dwcanillas
嗨,我非常感謝這個答案,但它似乎當我寫 static int sedan = 2,我得到一個錯誤,我必須使這個 const static int sedan = 2.如果它是const,我將無法減少和增加車輛。 – ricefieldboy
@ ricefieldboy對不起,編輯修復。你必須有一個初始化方法來初始化非常量的靜態變量。 – phantom