首页 > 解决方案 > 邓肯郊区总统超支?

问题描述

然后第二个文本无人驾驶毁了

标签: exit

解决方案


您的想法是正确的,但您的实施add()并不是最佳的。如果不出意外,它正在泄漏旧pets数组。但它的编码也比它需要的更复杂。

它应该看起来更像以下内容(假设pets并且在调用length之前已正确初始化,并且根据 3/5/0的规则正确管理它们,并且您的对象没有被代码中其他地方的另一个错误损坏) :add()PetArrayPetArray

void PetArray::add(Pet *p)
{
    Pet** temp = new Pet*[length+1];
    for(int i = 0; i < length; ++i)
    {
        temp[i] = pets[i];
    }
    temp[length] = p;
    
    delete[] pets;
    pets = temp;
    ++length;
}

更新:您没有add()正确地将对象添加到您的数组中。您在自动内存中创建派生对象,而不是在动态内存中。在对象超出范围并被销毁之前,您正在获取指向对象的指针,然后将现在无效的指针添加到数组中。

Pet* p;
...
if(species == "Cat"){
    ...
    Cat c(name, species, age, weight, length);
    p = &c;
} // <-- c is destroyed here!
// same goes for the other animal types, too...
...
add(p); // <-- p is invalid here!

这解释了您描述的两个问题。您正在添加指向在每次循环迭代中重用的本地内存的指针,然后在尝试访问无效对象时崩溃。

您需要改为new对象,例如:

Pet* p;
...
if(species == "Cat"){
    ...
    p = new Cat(name, species, age, weight, length);
}
// same for the other animal types, too...
...
add(p);

推荐阅读