search

Home  >  Q&A  >  body text

c++ - 继承析构顺序

以下程序输出什么?

class A
{
public:
    A()  {     }
    ~A() {    cout<<"~A"<<endl;   }
};

class B:public A
{
public:
    B(A &a):_a(a)//初始化列表
    {
        
    }
    ~B()
    {
        cout<<"~B"<<endl;
    }
private:
    A _a;
};
int main()
{
    A a;
    B b(a);
}
PHP中文网PHP中文网2805 days ago505

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-17 13:01:18

    Destruction and construction in C++ are opposite processes. The construction process is as follows: instance main in a, base class B part of A, member B of _a, B itself. Destruction is reversed, first B, then _a, then the base class, then a, so the output should be:

    ~B
    ~A
    ~A
    ~A

    reply
    0
  • Cancelreply