Order of calling constructors/destructors in inheritance(继承中调用构造函数/析构函数的顺序)
问题描述
关于创建对象的一个小问题.假设我有这两个类:
A little question about creating objects. Say I have these two classes:
struct A{
A(){cout << "A() C-tor" << endl;}
~A(){cout << "~A() D-tor" << endl;}
};
struct B : public A{
B(){cout << "B() C-tor" << endl;}
~B(){cout << "~B() D-tor" << endl;}
A a;
};
并且在 main 我创建了一个 B
的实例:
and in main I create an instance of B
:
int main(){
B b;
}
注意 B
派生自 A
并且还有一个 A
类型的字段.
Note that B
derives from A
and also has a field of type A
.
我想弄清楚规则.我知道构造对象时首先调用其父构造函数,析构时反之亦然.
I am trying to figure out the rules. I know that when constructing an object first calls its parent constructor, and vice versa when destructing.
字段(A a;
在这种情况下)呢?当B
被创建时,它什么时候会调用A
的构造函数?我还没有定义初始化列表,是否有某种默认列表?如果没有默认列表?还有关于破坏的同样问题.
What about fields (A a;
in this case)? When B
is created, when will it call A
's constructor? I haven't defined an initialization list, is there some kind of a default list? And if there's no default list? And the same question about destructing.
推荐答案
- 构造总是从基础
class
开始.如果有多个基class
,那么从最左边的基开始构造.(旁注:如果存在虚拟
继承,则优先级更高). - 然后构造成员字段.它们在声明它们的顺序
- 最后,
class
本身被构造 - 析构函数的顺序正好相反
- Construction always starts with the base
class
. If there are multiple baseclass
es then, construction starts with the left most base. (side note: If there is avirtual
inheritance then it's given higher preference). - Then the member fields are constructed. They are initialized in the order they are declared
- Finally, the
class
itself is constructed - The order of the destructor is exactly the reverse
- Base
class A
的构造函数 将构造 class B
的名为a
(类型class A
)的字段- 派生
class B
的构造函数 - Base
class A
's constructor class B
's field nameda
(of typeclass A
) will be constructed- Derived
class B
's constructor
不管初始化列表如何,调用顺序都是这样的:
Irrespective of the initializer list, the call order will be like this:
这篇关于继承中调用构造函数/析构函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承中调用构造函数/析构函数的顺序
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01