C++中析构函数和构造函数的调用顺序是什么

2021-12-30 00:00:00 constructor destructor c++

在C++中调用析构函数和构造函数的顺序是什么?使用一些基类和派生类的例子

解决方案

顺序是:

  1. 基础构造函数
  2. 派生构造函数
  3. 派生析构函数
  4. 基础析构函数

示例:

B 类{上市:乙(){cout<<构建体 B"<

示例输出:

<块引用>

构造 B

构造 D

破坏 D

销毁 B

多级继承就像一个堆栈:

如果您考虑将一个项目推入堆栈作为构造,而将其取出作为销毁,那么您可以像堆栈一样查看多个层次的继承.

这适用于任意数量的级别.

示例 D2 派生自 D 派生自 B.

将 B 推入堆栈,将 D 推入堆栈,将 D2 推入堆栈.所以施工顺序是B、D、D2.然后找出破坏顺序开始弹出.D2, D, B

更复杂的例子:

更复杂的例子,请看@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:

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

相关文章