zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    高可用的MongoDB集群-实战篇
    【转载】特征选择常用算法综述
    【转载】Pytorch tutorial 之Datar Loading and Processing
    论文笔记系列-Well Begun Is Half Done:Generating High-Quality Seeds for Automatic Image Dataset Construction from Web
    重新定义Pytorch中的TensorDataset,可实现transforms
    【转载】机器学习之特征工程
    Pytorch里的CrossEntropyLoss详解
    Python日志模块logging用法
    【转载】如何进行数据变换
    【转载】使用sklearn优雅地进行数据挖掘
  • 原文地址:https://www.cnblogs.com/liaocheng/p/4352956.html
Copyright © 2011-2022 走看看