[C++]虚析构函数

使用虚析构函数,才能调用子类的析构函数

virtual在函数中的使用限制

1.普通函数不能是虚函数
2.静态成员不能是虚函数
3.内联函数不能是虚函数
4.构造函数不能为虚函数

Shape.h

#ifndef SHAPE_H
#define SHAPE_H

#include 
using namespace std;

class Shape {
public:
    Shape();
    ~Shape();
    virtual double calcArea();
};

#endif 

Shape.cpp

#include "Shape.h"

Shape::Shape()
{
    cout << "Shape()" << endl;
}

Shape::~Shape() {
    cout << "~Shape()" << endl;
}

double Shape::calcArea()
{
    cout << "Shape->calcArea()" << endl;
    return 0;
}

Coordinate.h

#ifndef COORDINATE_H
#define COORDINATE_H

class Coordinate {
public:
    Coordinate(int x,int y);
    ~Coordinate();
private:
    int m_iX;
    int m_iY;
};

#endif 

Coordinate.cpp:

#include"Coordinate.h"
#include 
using namespace std;

Coordinate::Coordinate(int x, int y)
{
    cout << "Coordinate" << endl;
    m_iX = x;
    m_iY = y;
}

Coordinate::~Coordinate()
{
    cout << "~Coordinate()" << endl;
}

Circle.h

#ifndef  CIRCLE_H
#define CIRCLE_H

#include "Shape.h"
#include "Coordinate.h"

class Circle : public Shape{
public:
    Circle(double r);
    ~Circle();
    double calcArea();
protected:
    double m_dR;
    Coordinate *m_pCenter;
};

#endif 

Circle.cpp:

#include "Circle.h"

Circle::Circle(double r)
{
    cout << "Circle()" << endl;
    m_dR = r;
    m_pCenter = new Coordinate(3, 5);
}

Circle::~Circle()
{
    cout << "~Circle()" << endl;
    delete m_pCenter;
    m_pCenter = NULL;
}
 
double Circle::calcArea() {
    cout << "Ciecle->calcArea()" << endl;
    return 3.14*m_dR*m_dR;
}

demo.cpp:

#include "Circle.h"

int main(void)
{
    Shape *shape2 = new Circle(5);
    delete shape2;
    system("pause");
    return 0;

}

运行

[C++]虚析构函数_第1张图片
Paste_Image.png

修改

#ifndef SHAPE_H
#define SHAPE_H

#include 
using namespace std;

class Shape {
public:
    Shape();
    virtual~Shape();
    virtual double calcArea();
};

#endif 

[C++]虚析构函数_第2张图片
Paste_Image.png

你可能感兴趣的:([C++]虚析构函数)