我得到這個例子C++問題與多態性 - 數據覆蓋
父類Vehicle
子類Car
,Motorcycle
,& 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
菜單的一個提示,如果用戶選擇插入一個新的車輛,他選擇的車型,並且將手動輸入一些值一樣theName
和theYear
。然後它將被設置爲vehicletwod[arrayCounter]
。
如果vehicletwod
列表中有多個同一子類型的對象,則該程序會遇到問題。
如果用戶確實像
Car
Motorcycle
Car
的第一輛汽車價值將被最新Car
(2號車)被覆蓋
但是,如果他們輸入
Car
Motorcycle
Lorry
ITIS很好,因爲每個對象只運行一次。
如何更改我的聲明,使其不會覆蓋以前相同的子類的數據。
請顯示您操作arrayCounter的代碼。實際上,請僅顯示代碼,如果這太長,請將其縮減爲最簡單的代碼,然後再顯示問題。你要求人們用他們看不見的代碼來診斷問題。其中一個猜測可能是正確的,但無論是否,現在他們都猜測都是一樣的。 – jthill