当派生类不是立即派生而是从已经派生的类派生时,我对重写函数感到困惑。
#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的析构函数。我想知道是否仅要求最基本的类具有一个声明为virtual的析构函数,并且在这种情况下,所有继承自该类的其他类都具有虚构的析构函数,如果您了解我的意思,这些析构函数将覆盖其他更上游的析构函数。
我不确定我是否有意义,基本上,如果我有一系列的10个类,每个类都继承自最后一个类,那么链中的任何析构函数都将覆盖所有比其更基础的析构函数?
struct GreatGrandfather{~virtual GreatGrandfather(){}}; // Only this is necessary
struct Grandfather : GreatGrandfather {};
struct Father : Grandfather{};
struct Son : Father{};
struct Grandson : Son {};
struct GreatGrandson : Grandson{};
孙子的析构函数将覆盖其上面的所有类,但不是大孙子的析构函数?
而且,一旦将基类的析构函数或其他函数声明为虚拟的,则无需再次将其子代声明为虚拟的吗?
链中的任何析构函数都将覆盖所有比其更基础的析构函数?
是的,差不多。如果您不编写析构函数,则该实现将隐式提供析构函数。因此,它也将隐式覆盖基类d'tor。
孙子的析构函数将覆盖其上面的所有类,但不是大孙子的析构函数?
它将覆盖Son
'd'tor。扩展覆盖Father
的等等。是的 而且它无法覆盖GreatGrandson
,因为在其定义时,它无法展望未来并知道GreatGrandson
将存在。
而且,一旦将基类的析构函数或其他函数声明为虚拟的,则无需再次将其子代声明为虚拟的吗?
是的,与任何虚拟功能相同。一旦声明为虚拟,它在任何派生类中始终是虚拟的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句