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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)