#include <iostream>
#define PI 3.14
using namespace std;
class Shape{
protected:
double x,y; // 对于圆,x和y均表示圆的半径,而对于矩形,x表示矩形的长,y表示矩形的宽
public:
Shape(double _x,double _y);
double GetArea();
};
Shape::Shape(double _x,double _y):x(_x), y(_y){}
double Shape::GetArea()
{
return 0.0;
}
class Circle:public Shape{
double _r;
public:
Circle(double r); // 构造函数,并用r构造基类的x和y
double GetArea(); //求圆的面积
double GetRadius(); // 获取圆的半径
};
Circle::Circle(double r):Shape(r, r){}
double Circle::GetArea()
{
return PI*x*y;
}
double Circle::GetRadius()
{
return x;
}
class Rectangle:public Shape{
public:
Rectangle(double l,double w); // 构造函数,并用l和w构造基类的x和y
double GetArea(); // 求矩形的面积
double GetLength(); // 获取矩形的长
double GetWidth(); // 获取矩形的宽
};
Rectangle::Rectangle(double l,double w):Shape(l, w){}
double Rectangle::GetArea()
{
return x*y;
}
double Rectangle::GetLength()
{
return x;
}
double Rectangle::GetWidth()
{
return y;
}
int main()
{
Circle s1(1);
double area = s1.GetArea();
double r = s1.GetRadius();
cout<<"ciecle:r="<<r<<", area="<<area<<endl;
Rectangle s2(3,4);
area = s2.GetArea();
double l = s2.GetLength();
double w = s2.GetWidth();
cout<<"rectangle:length="<<l<<", width="<<w<<", area="<<area<<endl;
return 0;
}
c++求圆的面积和矩形的面积
最新推荐文章于 2024-08-10 10:46:27 发布