【问题标题】:C++ Car Inventory, copy constructor probsC++ Car Inventory,复制构造函数问题
【发布时间】:2016-02-11 05:45:19
【问题描述】:

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

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

【问题讨论】:

  • 为什么不使用std::vector&lt;Car&gt; cars
  • Proffesor 正在教我们向量的后端
  • 你如何确定元素没有被复制?显示使用该类的代码。

标签: c++ operator-overloading copy-constructor inventory


【解决方案1】:

在您的代码中,您可能缺少重新分配语句

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

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

x = car;

电机也类似!

希望这会有所帮助,但如果您想要动态数组,请尝试使用向量(obv 它们很快:p)

【讨论】:

  • 是的,但是 car 属于 List 类的新实例,现在它使用扩展数组创建新实例,但不复制数据
  • @jbrizown 如果您可以发布完整代码的链接,那就太好了。
  • 兄弟,我试图调试你的代码,但它有很多错误,所以我放弃了!
猜你喜欢
  • 1970-01-01
  • 2016-12-19
  • 2013-09-15
  • 2011-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多