exit - 邓肯郊区总统超支?
问题描述
然后第二个文本无人驾驶毁了
解决方案
您的想法是正确的,但您的实施add()
并不是最佳的。如果不出意外,它正在泄漏旧pets
数组。但它的编码也比它需要的更复杂。
它应该看起来更像以下内容(假设pets
并且在调用length
之前已正确初始化,并且根据 3/5/0的规则正确管理它们,并且您的对象没有被代码中其他地方的另一个错误损坏) :add()
PetArray
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()
正确地将对象添加到您的数组中。您在自动内存中创建派生对象,而不是在动态内存中。在对象超出范围并被销毁之前,您正在获取指向对象的指针,然后将现在无效的指针添加到数组中。
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);
推荐阅读
- python - 从外部环境运行 pyomo 时停止打开 cmd 窗口
- uwp - 在 VS2017 中使用证书对侧载应用程序进行签名有什么要求?
- android - Android 在类文件中给出未知常量标签 85
- python - pyplot 中的“figure.max_open_warning”...“可能会消耗太多内存”
- dictionary - 如何在kotlin的父映射中为子映射设置值?
- c++ - C++ 构造函数的问题。这里到底初始化了什么?
- java - Beehive框架可以在Tomcat上运行吗
- python - 在 Folium 中突出显示一个特定国家
- powershell - 在对象上找不到值的 Register-PSRepository 抛出错误
- aframe - Aframe 检查点和相机视图