类对象做成员与父类的构造与析构次序
在模拟C++考试时,经常遇上这种题目:一个派生类继承了一个父类对象,而且这个派生类中有一个类对象作为成员属性。这三个类都写了构造与析构函数,并在构造和析构时会输出相应的内容。这种题目本质上是在考察这几个类的构造和析构顺序。以下是一段简单的测试代码:
#include<iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "This is constructing Base" << endl;
}
~Base()
{
cout << "This is destroying Base" << endl;
}
};
class Member
{
public:
Member()
{
cout << "This is constructing Member" << endl;
}
~Member()
{
cout << "This is destroying Member" << endl;
}
};
class Derived : public Base
{
Member m;
public:
Derived()
{
cout << "This is condtructing Derived" << endl;
}
~Derived()
{
cout << "This is destroying Derived" << endl;
}
};
int main()
{
Derived d;
system("pause");
return 0;
}
输出结果
This is constructing Base
This is constructing Member
This is condtructing Derived
请按任意键继续. . .
This is destroying Derived
This is destroying Member
This is destroying Base
E:\C++_projects\Learning_projects\All_test\Debug\All_test.exe (进程 16200)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
所以,当一个类继承父类,且拥有一个类对象作为成员属性时,创建派生类对象会以以下顺序调用这几个类的构造函数: 父类 --> 成员类 --> 派生类 以相反的顺序析构: 派生类 --> 成员类 --> 父类 构造与析构的顺序相反是因为这几个类对象遵守出入栈原则:先进后出
|