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.
这篇关于是否在初始化变量之前调用了父类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否在初始化变量之前调用了父类构造函数?
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01