在初始化变量之前

在初始化变量之前

本文介绍了在初始化变量之前是否调用父类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在初始化变量之前调用父类构造函数,还是编译器首先初始化该类的变量?

Are parent class constructors called before initializing variables, or will the compiler initialize the variables of the class first?

例如:

class parent {
protected:
  int a;
public:
  parent() : a(123) {};
};

class child : public parent {
  int b;
public:
            // question: is parent constructor done before init b?
  child() : b(456), parent() {};
}


推荐答案

首先,只有最多
派生类(1.8)的构造函数,虚拟基类按照
的顺序初始化,它们出现在定向$ b的深度优先从左到右的遍历中$ b基类的非循环图,其中从左到右是在导出类
base-specifier-list中基类的外观的
的顺序。

— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base classes in the derived class base-specifier-list.

- 然后,直接基类在
声明顺序中初始化,因为它们出现在base-specifier-list
存储器初始化器)。

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

- 然后,非静态
数据成员按照它们在
类定义中声明的顺序进行初始化(同样不考虑
mem-initializers)。

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

- 最后,执行
构造函数体的复合语句。

— Finally, the compound-statement of the constructor body is executed.

这篇关于在初始化变量之前是否调用父类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:46