#include <iostream>
using namespace std;
class Animal{
public:
virtual void cry() = 0;
void eat();
};
class Cat:public Animal
{
public:
virtual void cry();
void grooming();
};
class Dog:public Animal
{
public:
virtual void cry();
void lash();
};
main()
{
Animal* animal = new Cat();
animal->eat();
animal->cry();
Cat* cat = (Cat*)animal;
cat->grooming();
Dog* dog = new Dog();
dog->cry();
dog->eat();
dog->lash();
delete animal; //Delete called on'animal' that is abstract but has non-virtual destruct
delete cat; //Thread 1: signal SIGABRT
delete dog;
}
Run Code Online (Sandbox Code Playgroud)
删除导致错误。这是为什么?尝试在不使用析构函数的情况下通过delete释放内存,但出现错误“Delete called on'animal' that is abstract but has non-virtual destruct Thread 1: signal SIGABRT”
Fan*_*Fox 10
该错误告诉您问题是什么。您正在使用非虚拟析构函数销毁虚拟对象。
你有virtual void cry为什么吗?这样当你打电话时animal->cry,它会发出Cat哭声,而不是默认的Animal哭声。虚拟析构函数也是如此。当您调用时,delete animal您需要它调用实际对象的析构函数,而不仅仅是基类。您需要添加:
virtual ~Animal() = default;
Run Code Online (Sandbox Code Playgroud)
到你的动物课。
基类析构函数应该是公共和虚拟的,或者是受保护的和非虚拟的
至于第二个问题,双重删除:
delete animal; // deletes the object
delete cat; // deletes the same object again, because cat and animal point to
// the same place.
Run Code Online (Sandbox Code Playgroud)
有些人建议不要删除两次,我建议根本不要显式调用删除。使用智能指针:
auto animal = std::make_unique<Cat>();
Cat &cat = *animal;
animal->cry();
cat.cry(); // Calls the same function as above.
Run Code Online (Sandbox Code Playgroud)
唯一的指针将为您处理对象的删除。
| 归档时间: |
|
| 查看次数: |
8082 次 |
| 最近记录: |