析构函数如何在派生 class 中工作。 C++

How does destructor work in derived class. C++

#include<iostream>
using namespace std;
class A
{
protected:
    int a,b;
public:
    A(int i, int j)
    {
        a=i;
        b=j;
        cout<< "A initialized"<<endl;
    }
    ~A()
    {
        cout<< "\nDestructor in base class A"<<endl;
    }
};
class B
{
protected:
    int c,d;
public:
    B(int i, int j)
    {
        c=i;
        d=j;
        cout<< "\nB initialized"<<endl;
    }
    ~B()
    {
        cout<< "\nDestructor in base class B"<<endl;
    }
};
class C : public B, public A
{
    int e,f;
public:
    C(int m, int n, int o, int p, int q, int r): A(m,n), B(o,p)
    {
        e=q;
        f=r;
        cout<< "C initialized";
    }
    ~C()
    {
        cout<< "\nDestructor in derived class C"<<endl;
    }
void display(void)
    {
    cout<< "\nThe value of a is : "<<a;
    cout<< "\nThe value of b is : "<<b;
    cout<< "\nThe value of c is : "<<c;
    cout<< "\nThe value of d is : "<<d;
    cout<< "\nThe value of e is : "<<e;
    cout<< "\nThe value of f is : "<<f;
    }
};
int main()
{
    C objc(10,20,30,40,50,60);
    objc.display();
    return 0;
}

我知道析构函数的调用顺序与构造函数调用的顺序相反。我想一步一步地了解上面代码中析构函数的实现,这样我就能理解它是如何工作的。请说明为什么以及如何以构造函数的相反顺序调用析构函数的原因。

为什么?因为从构造向后解构总是更安全和合乎逻辑。要建造房屋,您首先要建造地面,然后是墙壁和屋顶。如果你想摧毁它,你会倒着做:屋顶、墙壁和地面。

怎么样?这是由编译器完成的,他知道如何构建,然后他知道如何销毁。编译器知道变量的类型,因此它构建链(从继承图和结构组合推导出),然后在需要销毁它时反转链。