在派生类中重写哪个基类的虚拟析构函数
Which base class's virtual destructor is overriden in a derived class
当派生类不是立即派生的,而是从已经派生的类派生时,我对覆盖函数感到困惑。
#include <iostream>
struct Base
{
virtual ~Base() { std::cout << "Base destructor calledn"; }
};
struct Derived : Base
{
Derived() {}
// Implicitly supplied destructor, I'm guessing. Which is also virtual?
};
struct MostDerived : Derived
{
MostDerived(){};
~MostDerived() { std::cout << "MostDerived destructor calledn"; }
};
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
存在。
而且,一旦基类的析构函数或其他函数被声明为虚拟,它的后代就不需要再次声明为虚拟了吗?
是的,与任何虚拟功能相同。一旦声明为 virtual,它在任何派生类中始终是虚拟的。
构函数覆盖基类的所有虚拟析构函数,包括间接基。此外,覆盖虚拟函数的函数本身也是虚拟的。因此,是的,Derived
的隐式定义析构函数是虚拟的,~Base
和~Derived
都被~MostDerived
覆盖。当指向基类的指针用于销毁派生类类型的对象时,需要为虚拟的析构函数是基类的析构函数。 (派生类中的析构函数将是隐式虚拟的。
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 子类地址等于虚拟基类地址?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 虚拟基类函数中派生类的大小
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- 虚拟基类初始化
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 虚拟基类在内部如何工作?编译器如何解析对基方法的调用?
- 无法使用在子类中定义的虚拟getter实现基类
- C++虚拟函数:基类函数是调用的,而不是派生的
- 关于C++从派生类调用在基类中实现的虚拟函数的问题
- 派生类调用非公共基类虚拟函数
- 使用基类虚拟方法
- 强制调用基类虚拟函数
- 强制调用长链下的基类虚拟函数
- 通过派生类虚拟方法调用基类虚拟方法