在派生 class 中重写了哪个基础 class 的虚拟析构函数

Which base class's virtual destructor is overriden in a derived class

当派生 class 不是立即派生而是从已经派生的 class 派生时,我对覆盖函数感到困惑。

#include <iostream>

struct Base
{ 
    virtual ~Base() { std::cout << "Base destructor called\n"; }
};

struct Derived : Base
{
    Derived() {}
    // Implicitly supplied destructor, I'm guessing. Which is also virtual?
};

struct MostDerived : Derived
{
    MostDerived(){};
    ~MostDerived() { std::cout << "MostDerived destructor called\n"; }
};

int main()
{
    Derived* d = new MostDerived();
    delete d;
    Base* b = new MostDerived();
    delete b;
}

在这两种情况下,都会调用 MostDerived 的析构函数。我想知道是否只需要最基本的 class 有一个声明为虚拟的析构函数,在这种情况下,所有其他从它继承的 classes 都有虚拟析构函数,这些析构函数会覆盖更上游的所有其他析构函数,如果你明白我的意思。

我不确定我是否说得通,基本上如果我有一系列 10 个 classes,每个都继承自最后一个,链中的任何析构函数都会覆盖所有析构函数比它更基础?

struct GreatGrandfather{~virtual GreatGrandfather(){}}; // Only this is necessary
struct Grandfather : GreatGrandfather {};
struct Father : Grandfather{};
struct Son : Father{};
struct Grandson : Son {};
struct GreatGrandson : Grandson{};

孙子的析构函数将覆盖其上方的所有 classes,但不会覆盖曾孙的析构函数?

而且,一旦基 class 的析构函数或其他函数被声明为虚拟 none,其后代是否需要再次声明为虚拟?

any destructor in the chain will override all the destructors that are more base than it?

是的,差不多。如果您不编写析构函数,则实现将隐式提供析构函数。所以它也将隐式覆盖基础 class d'tor.

Grandson's destructor will override all of the classes above it, but not GreatGrandson's destructor?

它将覆盖 Son 的任务。通过扩展覆盖 Father 等等。所以是的。而且它不能覆盖 GreatGrandson,因为在它的定义点它无法展望未来并知道 GreatGrandson 将存在。

And also, once a base class's destructor or other function is declared virtual none of its descendants need to be declared virtual again?

是的,与任何虚函数一样。一旦声明为虚拟,它在任何派生 class.

中始终是虚拟的

析构函数覆盖基 classes 的所有虚拟析构函数,包括间接基。此外,覆盖虚函数的函数本身就是虚函数。因此,是的,Derived的隐式定义的析构函数是虚的,~Base~Derived都被~MostDerived覆盖了。当指向基 class 的指针用于销毁派生 class 类型的对象时,需要虚拟的析构函数是基 class 的析构函数。 (派生的 class 中的那个将隐含地是虚拟的。)