`

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

    博客分类:
  • C++
阅读更多
===============================================
未完待续,转载时请表明出处:http://www.cofftech.com/thread-1399-1-1.html
欢迎大家跟帖讨论哈~~~~~
===============================================
[例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))无关。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics