2012-10-30 22 views
0

我得到這個例子C++問題與多態性 - 數據覆蓋

父類Vehicle

子類CarMotorcycle,& Lorry

這是發生了什麼:在main.cpp創建

VehicleTwoD *vehicletwod[100]; 
Car *myCar = new Car(); 
Motorcycle *myMotorcycle = new motorCycle(); 
Lorry *myLorry = new Lorry(); 

這就是我d ○:

if(selection=="Car") 
{ 
    vehicletwod[arrayCounter] = myCar; 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 

if(selection=="Lorry") 
{ 
    vehicletwod[arrayCounter] = myLorry; 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 

if(selection=="Motorcycle") 
{ 
    vehicletwod[arrayCounter] = myMotorcycle ; 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 

cout << "Record successfully stored. Going back to the main menu " << endl; 

在這裏main.cpp的問題是某種switch-case菜單的一個提示,如果用戶選擇插入一個新的車輛,他選擇的車型,並且將手動輸入一些值一樣theNametheYear。然後它將被設置爲vehicletwod[arrayCounter]

如果vehicletwod列表中有多個同一子類型的對象,則該程序會遇到問題。

如果用戶確實像

Car 
Motorcycle 
Car 

的第一輛汽車價值將被最新Car(2號車)被覆蓋

但是,如果他們輸入

Car 
Motorcycle 
Lorry 

ITIS很好,因爲每個對象只運行一次。

如何更改我的聲明,使其不會覆蓋以前相同的子類的數據。

+0

請顯示您操作arrayCounter的代碼。實際上,請僅顯示代碼,如果這太長,請將其縮減爲最簡單的代碼,然後再顯示問題。你要求人們用他們看不見的代碼來診斷問題。其中一個猜測可能是正確的,但無論是否,現在他們都猜測都是一樣的。 – jthill

回答

1

您需要爲每個新條目創建一個新的Car,MotorcycleLorry實例,因爲現在您可以重新使用現有實例並以此方式重寫數據。你應該這樣做:

if(selection=="Car") 
{ 
    vehicletwod[arrayCounter] = new Car(); 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 

if(selection=="Lorry") 
{ 
    vehicletwod[arrayCounter] = new Lorry(); 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 

if(selection=="Motorcycle") 
{ 
    vehicletwod[arrayCounter] = new Motorcycle(); 
    vehicletwod[arrayCounter]->setName(theName); 
    vehicletwod[arrayCounter]->setYear(theYear); 
} 
1

每次選擇一個新的車輛時,必須創建一個全新的對象來保存它。更換你行:

vehicletwod[arrayCounter] = myCar; 

有:

vehicletwod[arrayCounter] = new Car; 

27:11其他類型。