继承与包含中构造与析构的执行顺序

来源:互联网 发布:beyonce 知乎 编辑:程序博客网 时间:2024/05/01 11:08

 

   [HP笔试题目]

    一个类A继承类B并且包含CB中包含D。在构造A的时候,先构造B中的D,再构造B,然后构造A中的C,最后构造A。虚构的过程刚好相反。例子如下:|

    #include<iostream.h>

class IDCart{

public:

         IDCart()

         {

                   cout<<"IDCart construstor"<<endl;

         }

         ~IDCart()

         {

                   cout<<"IDCart destrustor"<<endl;

         }

};

class person{

public:

         person()

         {

                   cout<<"person contrustor"<<endl;

         }

         ~person()

         {

                   cout<<"person destrustor"<<endl;

         }

private:

         IDCart id;

};

 

class subject{

public:

         subject()

         {

           cout<<"subject construstor"<<endl;

         }

         ~subject()

         {

           cout<<"subject destrustor"<<endl;

         }

};

 

class teacher:public person{

public:

          teacher()

          {

                    cout<<"teacher construstor"<<endl;

          }

          ~teacher()

          {

                    cout<<"teacher destrustor"<<endl;

          }

private:

         subject sub;

};

 

void main()

{

         teacher tea;

}

 

运行的结果如下:

IDCart construstor

person contrustor

subject construstor

teacher construstor

teacher destrustor

subject destrustor

person destrustor

IDCart destrustor