小编suh*_*han的帖子

为什么通过指向基类的指针删除数组时不调用派生类的(虚拟)析构函数?

我有一个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

43
推荐指数
4
解决办法
3601
查看次数