首页 > 编程语言 > 详细

(C++)C++类继承中的构造函数和析构函数

时间:2015-06-14 18:26:11      阅读:238      评论:0      收藏:0      [点我收藏+]

思想:

在C++的类继承中,

建立对象时,首先调用基类的构造函数,然后在调用下一个派生类的构造函数,依次类推;

析构对象时,其顺序正好与构造相反;

例子:

#include <iostream>
using namespace std;

class Shape{
public:
    void Draw() {cout<<"Base::Draw()"<<endl;}
    void Erase() {cout<<"Base::Erase()"<<endl;}
    Shape() {Draw();}
    ~Shape() {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;
}

结果:

技术分享

(C++)C++类继承中的构造函数和析构函数

原文:http://www.cnblogs.com/AndyJee/p/4575385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!