Initializer lists
In C++, it is the order of the class inheritance and of the member variables that determine the initialization order, not the order of an initializer list:


#include <iostream>
class CSomeClass

{
public:
CSomeClass(int n)

{
std::cout << "CSomeClass constructor with value ";
std::cout << n << std::endl;
}
};
class CSomeOtherClass

{
public:
CSomeOtherClass() //In this example, despite the list order,
: obj2(2), obj1(1) //obj1 will be initialized before obj2.

{
//Do nothing.
}
private:
CSomeClass obj1;
CSomeClass obj2;
};
int main(void)

{
CSomeOtherClass obj;
return 0;
}
本文通过一个具体的C++示例介绍了成员变量的初始化顺序是由它们在类中声明的顺序决定的,而不是由构造函数中初始化列表的顺序决定的。这有助于理解C++中对象初始化的底层机制。
1922

被折叠的 条评论
为什么被折叠?



