子对象构造函数和析构函数的调用顺序

#include<iostream>
using namespace std;
class sub_class
{
	int x;
	public:
	sub_class(int z)//构造函数
	{
		x=z;
		cout<<"Constructor_sub"<<x<<"called!"<<endl; 
	} 
	~sub_class(){
		cout<<"Destructor_sub"<<x<<"called!"<<endl;
	}
	void display()
	{
			cout<<x<<endl;}
} ;
class comp_class
{
	int y;
	sub_class s;
	sub_class r;
	public:
	comp_class(int z);
	void display_comp(){cout<<y<<endl;
	}
	void display_sub_s(){s.display();
	};
	void display_sub_r(){r.display();
	};
	~comp_class()
	{
		cout<<"Destructor_comp"<<y<<"called!"<<endl;
	}
		
};
comp_class::comp_class(int z):s(20),r(-36)
{
	y=z;
	cout<<"Constructor_comp"<<y<<"called!"<<endl; 
}
int main()
{
	comp_class obj(10);
	obj.display_sub_s();
	obj.display_sub_r();
	obj.display_comp();
}

Constructor_sub20called!
Constructor_sub-36called!
Constructor_comp10called!
20
-36
10
Destructor_comp10called!
Destructor_sub-36called!
Destructor_sub20called!

--------------------------------
Process exited after 6.22 seconds with return value 0
请按任意键继续. . .
调用对象成员的析构函数的顺序正好与调用构造函数的顺序相反

如果在成员初始化列表中将顺序颠倒为:

comp_class::comp_class(int z): r(-36)s(20)

{                            //define the constructor

       y = z;

       cout<<"Constructor_comp"<<y<<" called!"<<endl;

}

则运行结果仍然不变。

将class comp_class对象成员排列改变

class comp_class
{
	int y;
	sub_class r;
	sub_class s;
	public:
	comp_class(int z);
	void display_comp(){cout<<y<<endl;
	}
	void display_sub_s(){s.display();
	};
	void display_sub_r(){r.display();
	};
	~comp_class()
	{
		cout<<"Destructor_comp"<<y<<"called!"<<endl;
	}
		
};

Constructor_sub-36called!
Constructor_sub20called!
Constructor_comp10called!
20
-36
10
Destructor_comp10called!
Destructor_sub20called!
Destructor_sub-36called!


--------------------------------
Process exited after 1.774 seconds with return value 0
请按任意键继续. . .

运行结果发生改变。

调用对象成员的结构函数的顺序只决定于comp_class说明中对象成员的排列顺序,而与成员初始化列表中的顺序(r(-36)s(20))无关。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值