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 baseclasses then, construction starts with the left most base. (side note: If there is avirtualinheritance then it's given higher preference). - Then the member fields are constructed. They are initialized in the order they are declared
- Finally, the
classitself 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:
这篇关于继承中调用构造函数/析构函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承中调用构造函数/析构函数的顺序
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
