1. 静态成员最先构造,按照静态成员初始化顺序,不是类里面的声明顺序
2. 父类构造
3. 非静态成员构造,按照类成员声明顺序,不是逗号初始化成员顺序。 类成员声明时就地初始化早于逗号初始化。
4. 自身构造函数
Demo:
class TestA { public: TestA(){ std::cout << "TestA()" << std::endl; } }; class TestB { public: TestB(int b) { std::cout << "TestB()" << std::endl; } }; class TestC { public: TestC(int c) { std::cout << "TestC()" << std::endl; } }; class TestD { public: TestD() { std::cout << "TestD()" << std::endl; } }; class TestE { public: TestE() { std::cout << "TestE()" << std::endl; } }; class Father { public: Father() { std::cout << "Father()" << std::endl; } ~Father() { std::cout << "~Father()" << std::endl; } }; class SonA : public Father { public: SonA(int num1, int num2) :m_C(num1) ,m_B(num2)
,m_d(2) { std::cout << "SonA()" << std::endl; //先Father,最后Son
std::cout << "m_d:" << m_d << std::endl; //m_d逗号构造晚于类成员声明时就地初始化
} ~SonA() { std::cout << "~SonA()" << std::endl; } public: static TestD m_gD; static TestE m_gE; private: TestA m_A; TestB m_B; TestC m_C; //member声明顺序 A,B,C,逗号初始化顺序忽略
int m_d = 1; }; TestE SonA::m_gE; TestD SonA::m_gD; //static初始化顺序 E,D int main() { SonA son(1, 2); }
输出:
TestE() TestD() Father() TestA() TestB() TestC() SonA()
m_d:2