6

为什么在下面的示例中调用了所有析构函数 , , ~D()~C()~B()~A()

只有一个虚拟析构函数: of A

这是代码:

#include<iostream>
using namespace std;

class A
{
public:
  virtual ~A()
  {
    cout<<"destruct A\n";
  }

};
class B:public A
{
public:
  ~B()
  {
  cout<<"destruct B\n"; 
  }
};
class C:public B
{
public:
  ~C()
  {
    cout<<"destruct C\n";
  }
};
class D:public C
{
public:
   ~D()
   {
     cout<<"destruct D\n"; 
   }
};

int main()
{
    A* ptr = new D();
    delete ptr;
    return 0;
}
4

3 回答 3

7

The destruction order in derived objects goes in exactly the reverse order of construction: first the destructors of the most derived classes are called and then the destructor of the base classes.

A destructor can be defined as virtual or even pure virtual. You would use a virtual destructor if you ever expect a derived class to be destroyed through a pointer to the base class. This will ensure that the destructor of the most derived classes will get called:

A* b1 = new B;//if A has a virtual destructor
delete b1;//invokes B's destructor and then A's

A* b1 = new B;//if A has no virtual destructor
    delete b1;//invokes A's destructor ONLY

If A does not have a virtual destructor, deleting b1 through a pointer of type A will merely invoke A's destructor. To enforce the calling of B's destructor in this case we must have specified A's destructor as virtual:

virtual ~A();

REFERENCE

于 2012-10-17T05:45:05.910 回答
7

一旦A声明virtual了析构函数,所有派生类的析构函数也是virtual,即使它们没有明确声明为这样。所以你看到的行为正是预期的

于 2012-10-17T05:33:47.533 回答
0

正如@juanchopanza 所说 - 将基本析构函数声明为虚拟意味着所有后代都有虚拟析构函数。这种继承的虚拟性对于任何方法都是相同的,而不仅仅是析构函数。

这就是为什么我采访了不知道关键字做什么的人,因为他们只需要覆盖从框架派生的方法,所以它们都是虚拟的(叹气)。

于 2015-11-08T13:13:38.173 回答