《C++学习笔记》子对象构造函数和析构函数的调用顺序

===============================================
未完待续,转载时请表明出处:[url]http://www.cofftech.com/thread-1399-1-1.html[/url]
欢迎大家跟帖讨论哈~~~~~
===============================================
[例1]子对象的构造函数和析构函数的调用顺序
// cons_des_subobj_1.cpp
// To show the order in which the constructors and destructors are called
// 用于显示调用顺序的语句以下划线标出,其余语句均与程序initab_5.cpp相同

#include <iostream.h>
class sub_class {
int x;
public:
sub_class (int a) { x = a;
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 sub_obj_1; // a data member
sub_class sub_obj_2; // another data member
public:
comp_class (int a, int b, int c); //declaring the constructor
void display_comp( ) { cout<<"comp_class::y : "<<y<<endl; }
void display_sub_1( ) { cout<<"sub_obj_1.x : "; sub_obj_1.display( ); }
void display_sub_2( ) { cout<<"sub_obj_2.x : "; sub_obj_2.display( ); }
~comp_class()
{ cout<<"Destructor_comp "<<y<<" called!"<<endl; }
};

comp_class::comp_class (int a, int b, int c):sub_obj_1(b), sub_obj_2(c)
// constructor with initialization table
{
y = a;
cout<<"Constructor_comp : "<<y<<" called!"<<endl;
}

void main()
{
comp_class obj(10, 20, 30);
obj.display_comp();
obj.display_sub_1();
obj.display_sub_2();
}

/* Results:
Constructor_sub : 20 called!
Constructor_sub : 30 called!
Constructor_comp : 10 called!
comp_class::y : 10
sub_obj_1::x : 20
sub_obj_2::x : 30
Destructor_comp 10 called!
Destructor_sub : 30 called!
Destructor_sub : 20 called!
*/
以上程序中,系统先调用子对象的构造函数,后调用组合对象(主对象)的构造函数。。
此外,调用对象成员的析构函数的顺序正好与调用构造函数的顺序相反。 如果在成员初始化列表中将顺序颠倒为:
comp_class::comp_class (int a, int b, int c) : sub_obj_2(c), sub_obj_1(b) { …… } 则运行结果仍然不变。
但如改变comp_class类体中对象成员的排列顺序,例如:
class comp_class { int y;
sub_class sub_obj_2; // another data member
sub_class sub_obj_1; // a data member
…… …… }
则运行结果变为:
Constructor_sub : 30 called!
Constructor_sub : 20 called!
Constructor_comp : 10 called!
…… ……
Destructor_comp 10 called!
Destructor_sub : 20 called!
Destructor_sub : 30 called!
由此可见:调用对象成员(子对象)的构造函数的顺序只决定于复合类体中各子对象的排列顺序。而与成员初始化列表中的顺序(sub_obj_1(b), sub_obj_2(c))无关。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值