[HP笔试题目]
一个类A继承类B并且包含C,B中包含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
本文通过一个具体的C++示例程序展示了类继承及成员对象构造与析构的顺序。程序定义了四个类,包括IDCard、person、subject和teacher,并在main函数中创建了一个teacher对象。运行结果显示,构造过程按成员对象到派生类的顺序进行,而析构则顺序相反。
1069

被折叠的 条评论
为什么被折叠?



