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

    结果:

  • 相关阅读:
    win32获取其它进程变量地址存放的信息
    c#中的组件拖拽和MouseMove事件
    C# 使用消息驱动
    python使用dbm持久字典详解
    python http请求
    Windows 7下解决因为itunes备份导致C盘过度臃肿问题
    鼠标形状
    IE Haslayout 详解摘自网友
    Zoom属性摘自网友
    css公共属性
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4575385.html
Copyright © 2011-2022 走看看