繁体   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;
}

这给出以下输出:
阿托
电容
阿托
Btor
tor
tor

我不明白为什么会这样。 例如,我知道正在创建一个新的C对象,它是从A派生的,因此A ctor首先运行。 然后,ctor运行。 然后我以为C dtor运行了,但是由于某种原因A ctor再次运行了。

  1. 创建C,先构造A(基类),然后构造C
  2. 创建B,然后构造A(基类),然后B
  3. B被销毁(超出范围),这将销毁B,然后销毁A(基类)

C永远不会被删除,因此它会被泄漏并且析构函数也不会被调用。

暂无
暂无

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

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