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:
这篇关于继承中调用构造函数/析构函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承中调用构造函数/析构函数的顺序
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
