请设计一个描述形状的类Shape,Shape类中有两个成员函数:
(1) getArea()函数:用于计算
形状的面积。
(2) getLen()函数:用于计算形
状周长。
Shape类有两个派生类:
(1) Rectangle类:表示矩形。
(2) Circle类:表示圆形。
#ifndef _SHAPE_H_
#define _SHAPE_H_
#include <iostream>
using namespace std;
const double PI = 3.14;
class Shape{
public:
virtual double getLen() = 0;
virtual double getArea() = 0;
};
class Circle:public Shape{
public:
double getLen() {return 2.0 * PI * _radius;}
double getArea() {return PI * _radius * _radius;}
Circle(double r):_radius(r) {}
private:
double _radius;
};
class Rectangle:public Shape{
public:
Rectangle(double height,double width):_height(height),_width(width) {}
double getArea() {return _height * _width;}
double getLen() {return 2.0 *( _height + _width);}
private:
double _height, _width;
};
#endif
int main()
{
Rectangle myRect(1.0,2.0);
Circle myCircle(5.0);
cout <<"Rectangle area:" << myRect.getArea() << endl;
cout <<"Rectangle perimeter:" << myRect.getLen() << endl;
cout <<"Circle area:" << myCircle.getArea() << endl;
cout <<"Circle perimeter:" << myCircle.getLen() << endl;
}
Rectangle area:2
Rectangle perimeter:6
Circle area:78.5
Circle perimeter:31.4