問題描述
是在初始化變量之前調用父類的構造函數,還是編譯器會先初始化類的變量?
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.
這篇關于是否在初始化變量之前調用了父類構造函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!