gpt4 book ai didi

多态性的 C++ 问题 - 数据被覆盖

转载 作者:行者123 更新时间:2023-11-28 03:28:54 24 4
gpt4 key购买 nike

我得到了这个例子

父类Vehicle

子类 CarMotorcycleLorry

事情是这样的:在 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 菜单,因此如果用户选择插入新车辆,他会选择车辆类型,并将手动输入一些值,如 theNametheYear。然后它将被设置为 vehicletwod[arrayCounter]

vehicletwod 的列表中有超过 1 个相同子类型的对象时,程序会遇到问题。

如果用户做了类似的事情

Car
Motorcycle
Car

第 1 辆车的值将被最新的 Car(第 2 辆车)覆盖

但是,如果他们输入

Car 
Motorcycle
Lorry

很好,因为每个对象只运行一次。

如何更改我的声明,使其不会覆盖之前相同子类的数据。

最佳答案

您需要为每个新条目创建一个新的 CarMotorcycleLorry 实例,因为现在您可以重用现有实例并在这样重写数据。你应该这样做:

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);
}

关于多态性的 C++ 问题 - 数据被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13143333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com