057虚析构函数

上一篇中的动态多态可在某些情况下发生内存泄漏,通过虚析构函数避免。

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 <iostream>
using namespace std;

#include "Coordinate.h"

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

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

Shape.h

#ifndef SHAPE_H
#define SHAPE_H

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

#endif

Shape.cpp

#include "Shape.h"
#include <iostream>
using namespace std;

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

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

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

Rect.h

#ifndef RECT_H
#define RECT_H

#include "Shape.h"

class Rect : public Shape
{
public:
	Rect(double width, double height);
	virtual ~Rect();
	virtual double calcArea();
protected:
	double m_dWidth;
	double m_dHeight;
};


#endif

Rect.cpp


#include "Rect.h"
#include <iostream>
using namespace std;

Rect::Rect(double width, double height) : m_dWidth(width), m_dHeight(height)
{
	cout << "Rect" << endl;
}


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

double Rect::calcArea()
{
	cout << "Rect -> calcArea" << endl;
	return m_dWidth * m_dHeight;
}

Circle.h

#ifndef CIRCLE_H
#define CIRCLE_H

#include "Shape.h"
#include "Coordinate.h"
class Circle : public Shape
{
public:
	Circle(double r);
	virtual ~Circle();
	virtual double calcArea();
protected:
	double m_dR;
	Coordinate *m_pCenter;
};


#endif

Circle.cpp

#include "Circle.h"
#include <iostream>
using namespace std;

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

Circle::~Circle()
{
	cout << "~Circle" << endl;
	delete m_pCenter;
	m_pCenter = NULL;
}

double Circle::calcArea()
{
	cout << "Circle -> calcArea" << endl;
	return 3.14 * m_dR * m_dR;
}

demo.cpp

#include <iostream>
using namespace std;

#include "Shape.h"
#include "Rect.h"
#include "Circle.h"

int main()
{
	Shape *shape1 = new Rect(3,6);
	Shape *shape2 = new Circle(5);

	shape1->calcArea();
	shape2->calcArea();

	delete shape1;
	shape1 = NULL;
	delete shape2;
	shape2 = NULL;
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值