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;
}
删除导致错误。为什么呢?尝试在不使用析构函数的情况下通过delete释放内存,但发生错误删除调用抽象但非虚拟破坏的"动物"线程1:信号
错误告诉您问题所在。你正在用非虚构函数销毁虚对象。
你有virtual void cry
为什么?这样当你调用animal->cry
时,它会调用Cat
,而不是默认的Animal
。虚析构函数也是如此。当您调用delete animal
时,您需要它调用实际对象的析构函数,而不仅仅是基类。您需要添加:
virtual ~Animal() = default;
到你的动物班
基地类析构函数应该是public和virtual,或者是protected和non-virtual
Cpp核心指南
对于第二个问题,双重删除:
delete animal; // deletes the object
delete cat; // deletes the same object again, because cat and animal point to
// the same place.
有人建议不要删除两次,我建议根本不要显式调用delete。使用智能指针:
auto animal = std::make_unique<Cat>();
Cat &cat = *animal;
animal->cry();
cat.cry(); // Calls the same function as above.
唯一指针将为您处理对象的删除。
您试图删除同一个对象两次:
Animal* animal = new Cat();
Cat* cat = (Cat*)animal; // cat points to the same object as animal
...
delete animal; // first delete
delete cat; // second attemp fails