在C ++中调用析构函数和构造函数的顺序是什么 [英] What is the order in which the destructors and the constructors are called in C++

查看:125
本文介绍了在C ++中调用析构函数和构造函数的顺序是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

顺序是


  1. 基本构造函数

  2. 派生构造函数

  3. 派生析构函数

  4. 基础析构函数

  1. Base constructor
  2. Derived constructor
  3. Derived destructor
  4. 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:


构建B

Construct B

构造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 ++中调用析构函数和构造函数的顺序是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆