邓肯郊区总统超支?

Dunkin suburb president overrunning?

然后二文无人驾驶毁了

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

它应该看起来更像下面这样(假设 petslength 在调用 add() 之前正确初始化,并且 PetArray 正确地管理它们Rule of 3/5/0,并且您的 PetArray 对象没有被代码中其他地方的另一个错误损坏):

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()'ing 对象到你的数组。您正在 automatic 内存中创建派生对象,而不是在 dynamic 内存中。在对象超出范围并被销毁之前,您正在获取指向这些对象的指针,然后将现在无效的指针添加到您的数组中。

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