C++汽车清单,复制构造函数概率

C++ Car Inventory, copy constructor probs

本文关键字:复制 构造函数 概率 汽车 C++      更新时间:2023-10-16

所以我已经为这个分配而苦苦挣扎了一段时间。我修复了我所有的记忆问题(几天的逻辑),现在我被困在看似最简单的事情上。我必须在两个数组已满时扩展它们,这会扩展它们,但不复制数据,关于从这里开始的任何建议?

List::List(const List& x, int b)

{

if(b == 1)    // if car needs to grow
{
    size1 = x.size1 * 2;
    car = new Car[size1];
    for(int i = 0; i < count1; i++)
        car[i] = x.car[i];          // what copies .. I think...
}
else if(b == 2)            // if motorcycle array needs to grow
{
    size2 = x.size2 * 2;
    motor = new Motorcycle[size2];
    for(int i = 0; i < count2; i++)
    {
        motor[i] = x.motor[i];   // what copies .. I think...
    }   
}

}

我在这两个类中都有一个分配运算符重载

Car& Car::operator=( Car x)
{
    this->setModel(x.rModel()); 
    this->setMake(x.rMake());   
    this->setPrice(x.Vehicle::getPrice());
    this->setMileage(x.rMiles());
    this->setLot(x.rLot());
    this->setGas(x.rGas());
    this->seats = x.rSeats();
    this->luxury = x.rLux();    

}

摩托车也是如此

Motorcycle& Motorcycle::operator=( Motorcycle x)
{
    this->setModel(x.rModel()); 
    this->setMake(x.rMake());   
    this->setPrice(x.Vehicle::getPrice());
    this->setMileage(x.rMiles());
    this->setLot(x.rLot());
    this->setGas(x.rGas());
    this->style = x.rStyle();
    this->passenger = x.rPassenger();   
}

如果你帮我,我会把我拔掉的一缕头发送给你。

完整代码:https://drive.google.com/folderview?id=0B7LaFMkHcgCAd3habUpjWUR0YU0&usp=sharing

在你的代码中,你可能缺少一个重新赋值语句

car = new Car[size1];
for(int i = 0; i < count1; i++)
    car[i] = x.car[i]; 

在此之后,您应该添加另一行以使X再次指向汽车

x = car;

电机也类似!

希望这有帮助,但如果你想要动态阵列,请尝试使用矢量(OBV 它们:p很快)