虚析构函数

#include <iostream>
#include <cmath>
using namespace std;

#define PI 3.14

//几何图形类
class Geometry{
public:
    //获取面积
    virtual float getArea(){
        return 0;
    };
};

//矩形类
class Rectangle:public Geometry{//多态必须是共有继承
public:
    Rectangle(float minX,float minY,float maxX,float maxY)
    :minx(minX),miny(minY),maxx(maxX),maxy(maxY)
    {
        type = new char[20];
    }
    ~Rectangle(){
        if (type){//如果type有值
            delete []type;
        }
    }
public:
    float getArea(){
        return fabs((minx-maxx)*(miny-maxy));
    }
private:
    float minx,miny,maxx,maxy;
    char* type;
};

int main(int argc, const char * argv[]) {
    Geometry *g = new Rectangle(0,0,3,4);
    delete g;
    return 0;
}

打上断点,调试一下,可以发现可以成功申请20个字节的type但是delete g 的时候,并没有进入析构函数中。

给基类Geometry加一个析构函数

//几何图形类
class Geometry{
public:
    //获取面积
    virtual float getArea(){
        return 0;
    };
    ~Geometry(){

    }
};

再调试,发现还是没有进入Rectangle的析构器中😓

//几何图形类
class Geometry{
public:
    //获取面积
    virtual float getArea(){
        return 0;
    };
    virtual ~Geometry(){

    }
};

虚析构函数,ok,成功进入。

results matching ""

    No results matching ""