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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)