gpt4 book ai didi

c++ ctor 和 dtor 的工作方式不同

转载 作者:太空狗 更新时间:2023-10-29 21:21:14 26 4
gpt4 key购买 nike

<分区>

我正在尝试找出 C++ 中类继承的技巧,并且我构建了一个示例项目:

#include "stdafx.h"
#include <iostream>
using namespace std;

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

~A()
{
cout << "Class A destructed" << endl;
}
};

class B : public A
{
public:
B()
{
cout << "Class B initialized" << endl;
}

~B()
{
cout << "Class B destructed" << endl;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
cout << "A* a = new A()" << endl;
A* a = new A();
cout << "B* b = new B ()" << endl;
B* b = new B ();
cout << "A* ab = new B()" << endl;
A* ab = new B();

cout << "delete a" << endl;
delete a;
cout << "delete b" << endl;
delete b;
cout << "delete ab" << endl;
delete ab;

int i;
cin >> i;

return 0;
}

我得到的输出是:

A* a = new A()
Class A initialized
B* b = new B ()
Class A initialized
Class B initialized
A* ab = new B()
Class A initialized
Class B initialized
delete a
Class A destructed
delete b
Class B destructed
Class A destructed
delete ab
Class A destructed

我可以将类 B 的行为理解为派生类 - 首先它构造基类,然后构造派生类。当它调用析构函数时,它会以相反的方式进行工作。似乎合乎逻辑。

我无法理解的是 ab 的行为(我放入 A 指针的 B 的分配),为什么构造函数和纯B一样,而析构函数只运行在A上?

谢谢。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com