是否在初始化变量之前调用了父类构造函数?

Are parent class constructors called before initializing variables?(是否在初始化变量之前调用了父类构造函数?)

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

问题描述

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

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

例如:

class parent {
  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() {};
}

推荐答案

是的,基类在派生类成员和构造函数体执行之前初始化.

Yes, the base class is initialized before the members of the derived class and before the constructor body executes.

在非委托构造函数中,初始化在以下顺序:

In a non-delegating constructor, initialization proceeds in the following order:

——首先,并且只针对大多数的构造函数派生类(1.8),虚基类按顺序初始化它们出现在有向的从左到右的深度优先遍历中基类的非循环图,其中从左到右"是派生类中基类的外观基本说明符列表.

— 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.

——然后​​,直接基类在出现在基本说明符列表中的声明顺序(不管内存初始化器的顺序如何).

— 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).

——然后​​,非静态数据成员按照它们在类定义(同样不管内存初始化器).

— 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.

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

本文标题为:是否在初始化变量之前调用了父类构造函数?

基础教程推荐