问题描述
C ++中析构函数和构造函数的调用顺序是什么?使用一些Base类和派生类的示例
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
推荐答案
顺序是:
- 基本构造函数
- 派生构造函数
- 派生析构函数
- 基础析构函数
- Base constructor
- Derived constructor
- Derived destructor
- Base destructor
示例: b $ b
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;
}
输出示例: b
$ b
Output of example:
构造D
Destruct D
Destruct D
Destruct B
Destruct B
像堆栈一样工作:
如果你考虑将一个项目推送到堆栈作为构造,并将其作为销毁,然后你可以查看多个级别的继承就像一个堆栈。
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.
示例D2派生自D派生自B。
Example D2 derives from D derives from B.
在堆栈上推B,在堆栈上推D,在堆栈上推D2。因此施工顺序为B,D,D2。然后找出销毁命令开始弹出。 D2,D,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
更复杂的示例:
,请参阅@JaredPar
For more complicated examples, please see the link provided by @JaredPar
这篇关于在C ++中调用析构函数和构造函数的顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!