0

私はこの例を得ました

親クラスVehicle

子クラスCarMotorcycle、 &Lorry

これが起こることですmain.cpp:

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

これが私がすることです:

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

1号車の値は最新Car(2号車)に上書きされます

ただし、入力すると

Car 
Motorcycle
Lorry

各オブジェクトは一度しか実行されないので問題ありません。

以前の同じ子クラスのデータを上書きしないように宣言を変更するにはどうすればよいですか。

4

2 に答える 2

1

既存のインスタンスを再利用してデータを書き換えるので、新しいエントリごとに新しい と インスタンスCarを作成する必要がありMotorcycleます。Lorryやったほうがいい:

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);
}
于 2012-10-30T16:21:32.320 に答える
1

新しい車両を選択するたびに、それを保持するための新しいオブジェクトを作成する必要があります。あなたの行を置き換えます:

vehicletwod[arrayCounter] = myCar;

と:

vehicletwod[arrayCounter] = new Car;

他のタイプについても同様です。

于 2012-10-30T16:21:49.170 に答える