快快喜欢我 2021-06-08 09:33 采纳率: 20%
浏览 200

用c++派生求圆,长方形,正方形的面积

【问题描述】已知下面Shape类的定义,在此基础上派生出Rectangle和Circle类,二者都有GetArea()函数,用于计算对象的面积。再使用Rectangle类创建一个派生类Square。

自行根据需要定义相关的成员,达到以下要求:

(1)达到以上题目所规定的类族要求。

(2)编写主函数,能够动态生成半径为5的圆对象的创建,并实现面积计算和输出。

(3)主函数中能动态生成长为4,宽为6的矩形对象创建,并实现面积计算和输出。

(4)主函数中能动态生成边为5的正方形对象创建,并实现面积计算和输出。

(5)完成上述动态对象的释放。

【输入形式】无输入。

【输出形式】分别输出指定圆、长方形和正方形的面积。

【样例输入】无输入

【样例输出】

The area of the Cirele is:78.5

The area of the Recanale is:24

The area of the Recanale is:25

  • 写回答

1条回答 默认 最新

  • qfl_sdu 2021-06-08 10:16
    关注

    代码如下,如有帮助,请采纳一下,谢谢。

    #include <iostream>
    using namespace std;
    const double PI = (float)3.14159;
    class Shape
    {
    public:
    	virtual double GetArea() = 0;
    };
    //长方形
    class Rectangle:public Shape
    {
    private:
    	double width;  //宽
    	double length; //长
    public:
    	Rectangle(double l,double w):width(w),length(l){}
    	double GetArea(){return width * length;}
    	double GetWidth(){return width;}
    	double GetLength(){return length;}
    };
    //圆形
    class Circle : public Shape
    {
    private:
    	double radius;
    public:
    	Circle(double r):radius(r){}
    	double GetArea(){return PI * radius * radius;}
    	double GetRadius(){return radius;}
    };
    int main()
    {
    	char buf[10] = {0};
    	Circle* cc =new Circle(5);
    	sprintf_s(buf,10,"%.1f",cc->GetArea());
    	cout << "The area of the Cirele is:" <<  buf <<endl;
    	Rectangle* r1 = new Rectangle(4,6);
    	cout << "The area of the Recanale is:" << r1->GetArea() << endl;
    	Rectangle* r2= new Rectangle(5,5);
    	cout << "The area of the Recanale is:" << r2->GetArea() << endl;
    	delete cc;
    	delete r1;
    	delete r2;
    	return 0;
    }
    评论

报告相同问题?

悬赏问题

  • ¥15 根据时间在调用出列表
  • ¥15 FastReport.community 编辑,table只显示“每页”最顶部和底部横线
  • ¥15 R 包chipseeker 安装失败
  • ¥15 Veeam Backup & Replication 9.5 还原问题
  • ¥15 vue-print-nb
  • ¥15 winfrom的datagridview下拉框变成了黑色,渲染不成功
  • ¥20 利用ntfy实现短信推送
  • ¥30 如何用VBA代码写抽取TRIBON M3数据库的模型信息
  • ¥15 MySQL好难呀,怎么呀
  • ¥15 如何用Thonny写温湿度检测有源蜂鸣器报警并在oled屏上显示的代码?