我有一个Animal带有虚拟析构函数的类和一个派生类Cat。
#include <iostream>
struct Animal
{
Animal() { std::cout << "Animal constructor" << std::endl; }
virtual ~Animal() { std::cout << "Animal destructor" << std::endl; }
};
struct Cat : public Animal
{
Cat() { std::cout << "Cat constructor" << std::endl; }
~Cat() override { std::cout << "Cat destructor" << std::endl; }
};
int main()
{
const Animal *j = new Cat[1];
delete[] j;
}
Run Code Online (Sandbox Code Playgroud)
这给出了输出:
动物构造函数
猫构造函数
动物析构函数
我不明白Cat当我的基类析构函数是虚拟的时,为什么不调用 的析构函数?
c++ arrays polymorphism inheritance dynamic-memory-allocation