[英]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再次运行了。
C is never deleted, so it's leaked and the destructors are never called. C永远不会被删除,因此它会被泄漏并且析构函数也不会被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.