定义一个基类shape,再次基础上派生出 长方形,正方形,圆形,二者都有getArea()计算对象的面积
#include <iostream>
using namespace std;
//基类 shape
class Shape {
public:
Shape() {}
~Shape() {}
virtual float getArea() {
return -1;
}
};
//派生类 圆形
class Circle :public Shape {
public:
Circle(float radius):itsRadius(radius){}
~Circle(){}
float getArea() {
return 3.14 * itsRadius * itsRadius;
}
private:
float itsRadius;
};
//派生类 长方形
class Rectangle :public Shape {
public:
Rectangle(float len, float width) :itsLength(len), itsWidth(width) {};
~Rectangle(){}
virtual float getArea() {
return itsLength * itsWidth;
}
virtual float getLength() {
return itsLength;
}
virtual float getWidth() {
return itsWidth;
}
private:
float itsWidth;
float itsLength;
};
//正方形
class Square :public Rectangle {
public:
Square(float len);
~Square() {}
};
Square::Square(float len) :Rectangle(len, len) {
}
int main() {
Shape* sp;
sp = new Circle(5);
cout << "圆形的面积:" << sp->getArea() << endl;
delete sp;
sp = new Rectangle(4, 6);
cout << "长方形的面积:" << sp->getArea() << endl;
delete sp;
sp = new Square(5);
cout << "正方形的面积:" << sp->getArea() << endl;
delete sp;
return 0;
}