简体   繁体   English

为什么这是该程序的输出?

[英]Why is this the output of this program?

#include <iostream>
using namespace std;


class  A
{
public:
    A()
    {
        cout << "A ctor" << endl;
    }
    virtual ~A()
    {
        cout << "A dtor" << endl;
    }
    virtual void foo() = 0;
};
class  B : public A
{
public:
    B()
    {
        cout << "B ctor" << endl;
    }
    virtual ~B()
    {
        cout << "B dtor" << endl;
    }
    virtual void foo()
    {
        cout <<"B's foo" << endl;
    }
};
class  C : public A
{
public:
    C() {
        cout << "C ctor" << endl;
    }
    virtual ~C()
    {
        cout << "C dtor" << endl;
    }
    virtual void foo() {cout << "C's foo" << endl;
    }
}; 

int  main ()
{

    C *ptr = new C[1];
    B b;
    return 0;
}

This gives the following output: 这给出以下输出:
A ctor 阿托
C ctor 电容
A ctor 阿托
B ctor Btor
B dtor tor
A dtor tor

I don't understand why this is happening. 我不明白为什么会这样。 For example, I know that a new C object is being created, that's derived from A, so the A ctor runs first. 例如,我知道正在创建一个新的C对象,它是从A派生的,因此A ctor首先运行。 Then the C ctor runs. 然后,ctor运行。 And then I thought the C dtor runs, but for some reason the A ctor is running again. 然后我以为C dtor运行了,但是由于某种原因A ctor再次运行了。

  1. C is created, this constructs A (base class) and then C 创建C,先构造A(基类),然后构造C
  2. B is created, this constructs A (base class) and then B 创建B,然后构造A(基类),然后B
  3. B is destroyed (goes out of scope), this destructs B and then A (base class) B被销毁(超出范围),这将销毁B,然后销毁A(基类)

C is never deleted, so it's leaked and the destructors are never called. C永远不会被删除,因此它会被泄漏并且析构函数也不会被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM