您的位置:首页 > 其它

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

2016-10-02 10:22 351 查看
#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-3610Destructor_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-3610Destructor_comp10called!Destructor_sub20called!Destructor_sub-36called!--------------------------------Process exited after 1.774 seconds with return value 0请按任意键继续. . .运行结果发生改变。调用对象成员的结构函数的顺序只决定于comp_class说明中对象成员的排列顺序,而与成员初始化列表中的顺序(r(-36),s(20))无关。
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: