继承中调用构造函数/析构函数的顺序

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 base classes then, construction starts with the left most base. (side note: If there is a virtual inheritance then it's given higher preference).
    • Then the member fields are constructed. They are initialized in the order they are declared
    • Finally, the class itself is constructed
    • The order of the destructor is exactly the reverse
    • 不管初始化列表如何,调用顺序都是这样的:

      Irrespective of the initializer list, the call order will be like this:

      1. Base class A 的构造函数
      2. 将构造
      3. class B 的名为a(类型class A)的字段
      4. 派生class B的构造函数
      1. Base class A's constructor
      2. class B's field named a (of type class A) will be constructed
      3. Derived class B's constructor

      这篇关于继承中调用构造函数/析构函数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:继承中调用构造函数/析构函数的顺序

基础教程推荐