用 c++
编写一个程序,建立一个形状类 Shape
作为抽象基类,派生出:圆类 Circle
和矩形类 Rectangle
,分别获取相关信息并计算面积。 具体要求如下:
(1)基类 Shape
(a)保护数据成员 double x,y
:对于不同的形状,x
和 y
表示不同的含义,如对于圆,x
和 y
均表示圆的半径,而对于矩形,x
表示矩形的长,y
表示矩形的宽。访问权限定义为保护类型是为了能被继承下去,以便派生类能直接访问x和y。 (b)公有成员函数 构造函数 Shape(double _x,double _y)
:用 _x、_y
分别初始化 x、y
。 double GetArea()
:求面积,在此返回 0.0
。
(2)矩形类 Rectangle
,从 Shape
公有派生,其公有成员函数包括: Rectangle(double l,double w)
:构造函数,并用 l
和 w
构造基类的 x
和 y
。 double GetArea():
求矩形的面积。 double GetLength():
获取矩形的长。 double GetWidth()
:获取矩形的宽。
(3)在主函数中对派生类进行测试。
输入描述:
矩形类的长、宽
输出描述:
矩形类的面积值,要求输出结果保留两位小数
#include <iostream>
using namespace std;
class Shape {
protected:
double x, y;
public:
Shape(double _x, double _y) : x(_x), y(_y) {}
double GetArea() { return 0.0; }
};
class Rectangle : public Shape {
public:
Rectangle(double l, double w) : Shape(l, w) {} //继承基类
double GetArea() { return x * y; }
double GetLength() { return x; }
double GetWidth() { return y; }
};
int main() {
double l, w;
cin >> l >> w;
Rectangle rect(l, w);
printf("%.2f", rect.GetArea()); //保留两位小数
return 0;
}