码迷,mamicode.com
首页 > 编程语言 > 详细

c++构造顺序

时间:2019-11-06 22:58:15      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:stat   bsp   div   end   cpp   vat   逗号   mem   public   

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)
	{
		std::cout << "SonA()" << std::endl;   //先Father,最后Son
	}
	~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,逗号初始化顺序忽略
};

TestE SonA::m_gE;
TestD SonA::m_gD;   //static初始化顺序 E,D

int main()
{
	SonA son(1, 2);
}

输出:

TestE()
TestD()
Father()
TestA()
TestB()
TestC()
SonA()

  

 

 

c++构造顺序

标签:stat   bsp   div   end   cpp   vat   逗号   mem   public   

原文地址:https://www.cnblogs.com/leehm/p/11809015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!