Shape.h
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
Shape();
~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);
~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"
class Circle : public Shape
{
public:
Circle(double r);
~Circle();
virtual double calcArea();
protected:
double m_dR;
};
#endif
Cirlce.cpp
#include "Circle.h"
#include <iostream>
using namespace std;
Circle::Circle(double r) : m_dR(r)
{
cout << "Circle" << endl;
}
Circle::~Circle()
{
cout << "~Circle" << endl;
}
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;
}