(C++)C++類繼承中的構造函數和析構函數


思想:

在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;
}

結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM