快快喜欢我 2021-06-15 08:42 采纳率: 20%
浏览 43

用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条回答 默认 最新

  • 「已注销」 2023-03-17 06:17
    关注

    参考GPT和自己的思路:

    好的,根据您的问题,以下是一个可能的C++代码实现,希望能够帮到您:

    #include <iostream>
    using namespace std;
    
    // Shape类,基类
    class Shape {
    public:
        virtual double GetArea() = 0; // 纯虚函数
    };
    
    // Rectangle类,派生自Shape类
    class Rectangle : public Shape {
    public:
        Rectangle(double w, double h) : width(w), height(h) {} // 构造函数,初始化长和宽
        double GetArea() { return width * height; } // 计算面积的函数
    private:
        double width;
        double height;
    };
    
    // Circle类,派生自Shape类
    class Circle : public Shape {
    public:
        Circle(double r) : radius(r) {} // 构造函数,初始化半径
        double GetArea() { return 3.14 * radius * radius; } // 计算面积的函数
    private:
        double radius;
    };
    
    // Square类,派生自Rectangle类
    class Square : public Rectangle {
    public:
        Square(double s) : Rectangle(s, s) {} // 构造函数,初始化长度和宽度为边长
    };
    
    int main() {
        // 动态生成圆对象
        Circle* c = new Circle(5);
        double area_c = c->GetArea();
        cout << "The area of the Cirele is:" << area_c << endl;
    
        // 动态生成长方形对象
        Rectangle* r = new Rectangle(4, 6);
        double area_r = r->GetArea();
        cout << "The area of the Recanale is:" << area_r << endl;
    
        // 动态生成正方形对象
        Square* s = new Square(5);
        double area_s = s->GetArea();
        cout << "The area of the Recanale is:" << area_s << endl;
    
        // 释放动态对象
        delete c;
        delete r;
        delete s;
    
        return 0;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python怎么学啊最基础的解答一下
  • ¥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好难呀,怎么呀