zoukankan      html  css  js  c++  java
  • C++ 类的多态四(虚析构函数的重要性)

    //虚析构函数的重要性
    #include<iostream>
    using namespace std;
    /*
    虚析构函数
      主要用在多态中,用来释放子类对象内存空间,如果不使用虚析构函数,
      那么在多态的场景下,使用delete关键字只能执行父类析构函数
    
      子类对象中没有父类对象
    
      父类中有虚函数,子类中重写了该虚函数,那么默认子类中重写的函数也是虚函数,子类中不写virtual关键字也可以
      但是为了代码的可读性,还是在子类中也加上virtual 关键字
    */
    
    class Point{
    public:
        Point(int b=0){
            this->b = b;
        }
        virtual ~Point(){
            cout << "我是父类的析构函数!" << endl;
        }
    private:
        int b;
    };
    
    class PointA :public Point{
    public:
        virtual ~PointA(){
            cout << "我是子类的析构函数!" << endl;
        }
    };
    
    void ProtectA(Point *pin){
        //释放内存空间
        delete pin;
        //通过运行结果发现,如果不使用虚析构函数,那么传递过来的是子类对象
        //c++编译器也只会执行父类的析构函数  不会执行子类的析构函数
    }
    
    void ProtectB(){
        //在堆上分配内存空间
        PointA *pa = new PointA();
        ProtectA(pa);
    }
    
    void main(){
        ProtectB();
        system("pause");
    }

  • 相关阅读:
    [HDOJ1800]Flying to the Mars
    [HDOJ5058]So easy
    HDU 2819 — Swap 二分匹配
    POJ1236
    Codeforces Round #267 (Div. 2) C. George and Job DP
    codeforces Round #263(div2) D. Appleman and Tree 树形dp
    HDU 4345 Permutation dp
    HDU 4349 Xiao Ming's Hope lucas定理
    HDU 4342History repeat itself 数学
    HDU 4341 分组背包
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5635845.html
Copyright © 2011-2022 走看看