What is the order in which the destructors and the constructors are called in C++(C++中析构函数和构造函数的调用顺序是什么)
问题描述
在C++中调用析构函数和构造函数的顺序是什么?使用一些基类和派生类的例子
顺序是:
- 基础构造函数
- 派生构造函数
- 派生析构函数
- 基础析构函数
示例:
B 类{上市:乙(){cout<<构建体 B"<
示例输出:
<块引用>构造 B
构造 D
破坏 D
销毁 B
多级继承就像一个堆栈:
如果您考虑将一个项目推入堆栈作为构造,而将其取出作为销毁,那么您可以像堆栈一样查看多个层次的继承.
这适用于任意数量的级别.
示例 D2 派生自 D 派生自 B.
将 B 推入堆栈,将 D 推入堆栈,将 D2 推入堆栈.所以施工顺序是B、D、D2.然后找出破坏顺序开始弹出.D2, D, Bp>
更复杂的例子:
更复杂的例子,请看@JaredPar提供的链接
What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes
The order is:
- Base constructor
- Derived constructor
- Derived destructor
- Base destructor
Example:
class B
{
public:
B()
{
cout<<"Construct B"<<endl;
}
virtual ~B()
{
cout<<"Destruct B"<<endl;
}
};
class D : public B
{
public:
D()
{
cout<<"Construct D"<<endl;
}
virtual ~D()
{
cout<<"Destruct D"<<endl;
}
};
int main(int argc, char **argv)
{
D d;
return 0;
}
Output of example:
Construct B
Construct D
Destruct D
Destruct B
Multiple levels of inheritance works like a stack:
If you consider pushing an item onto the stack as construction, and taking it off as destruction, then you can look at multiple levels of inheritance like a stack.
This works for any number of levels.
Example D2 derives from D derives from B.
Push B on the stack, push D on the stack, push D2 on the stack. So the construction order is B, D, D2. Then to find out destruction order start popping. D2, D, B
More complicated examples:
For more complicated examples, please see the link provided by @JaredPar
这篇关于C++中析构函数和构造函数的调用顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中析构函数和构造函数的调用顺序是什么


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01