C++类的继承中构造函数和析构函数调用顺序例子

/*当建立一个对象时,首先调用基类的构造函数,然后调用下一个派生类的
构造函数,依次类推,直至到达派生类次数最多的派生次数最多的类的构造函数为止。
简而言之,对象是由“底层向上”开始构造的。因为,构造函数一开始构造时,总是
要调用它的基类的构造函数,然后才开始执行其构造函数体,调用直接基类构造函数时,
如果无专门说明,就调用直接基类的默认构造函数。在对象析构时,其顺序正好相反。
下面的这个程序说明这个问题*/
//-------------------------------------------------
#include <iostream>
using namespace std;
class Shape
{
public:
void Draw() {cout<<"Base::Draw()"<<endl;}
void Erase() {cout<<"Base::Erase()"<<endl;}
Shape() {Draw();} //基类构造函数,调用上面的Draw函数体
virtual ~Shape() {Erase();}//基类析构函数,调用上面的Erase函数体
};
//-------------------------------------------------
class Polygon:public Shape
{
public:
Polygon() {Draw();}
void Draw() {cout<<"Polygon::Draw()"<<endl;}
void Erase() {cout<<"Polygon Erase()"<<endl;}
~Polygon() {Erase();}
};
//--------------------------------------------------
class Rectangle:public Polygon
{
public:
Rectangle() {Draw();}
void Draw() {cout<<"Rectangle::Draw()"<<endl;}
void Erase() {cout<<"Rectangle Erase()"<<endl;}
~Rectangle() {Erase();}
};
//--------------------------------------------------
class Square:public Rectangle
{
public:
Square() {Draw();}
void Draw() {cout<<"Square::Draw()"<<endl;}
void Erase() {cout<<"Square Erase()"<<endl;}
~Square() {Erase();}
};
//--------------------------------------------------
int main()
{
Polygon c;
Rectangle s;
Square t;
cout<<"------------------------------------------"<<endl;
return 0;
}
//------------------------------------------

运行结果:

Base::Draw()
Polygon::Draw()
Base::dRAW()
Polygon::Draw()
Rectangle::Draw()
Base::dRAW()
Polygon::Draw()
Rectangle::Draw()
Square::Draw()
------------------------------------------
Square Erase()
Rectangle Erase()
Polygon Erase()
Base::Erase()
Rectangle Erase()
Polygon Erase()
Base::Erase()
Polygon Erase()
Base::Erase()
Press any key to continue

原文地址:https://www.cnblogs.com/liaocheng/p/4352956.html