Shape.h:
#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>
using namespace std;
class Shape {
public:
Shape();
~Shape();
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;
}
Circle.h
#ifndef CIRCLE_H
#define CIRCLE_H
#include "Shape.h"
class Circle : public Shape{
public:
Circle(double r);
~Circle();
double calcArea();
protected:
double m_dR;
};
#endif
Circle.cpp
#include "Circle.h"
Circle::Circle(double r)
{
cout << "Circle()" << endl;
m_dR = r;
}
Circle::~Circle()
{
cout << "~Circle()" << endl;
}
double Circle::calcArea() {
cout << "Ciecle->calcArea()" << endl;
return 3.14*m_dR*m_dR;
}
Rect.h
#ifndef RECT_H
#define RECT_H
#include "Shape.h"
class Rect :public Shape
{
public:
Rect(double witdth, double height);
~Rect();
double calcArea();
protected:
double m_dWith;
double m_dHeight;
};
#endif
Rect.cpp:
#include "Rect.h"
Rect::Rect(double witdth, double height) {
cout << "Rect()" << endl;
m_dWith = witdth;
m_dHeight = height;
}
Rect::~Rect() {
cout << "~Rect()" << endl;
}
double Rect::calcArea()
{
cout<<"Rect->calcArea()"<<endl;
return m_dWith*m_dHeight;
}
运行
添加virtual:
#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>
using namespace std;
class Shape {
public:
Shape();
~Shape();
virtual double calcArea();
};
#endif
运行