【几何图形的继承和派生】

该程序定义了一个基类Shape,包含纯虚函数GetArea()。派生了Rectangle(矩形)、Circle(圆形)类,并实现了GetArea()来计算面积。此外,还创建了继承自Rectangle的Square(正方形)类。主函数中动态创建了半径为5的圆、长为4宽为6的矩形以及边长为5的正方形对象,计算并输出了它们的面积。
摘要由CSDN通过智能技术生成

【问题描述】已知下面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

【程序说明】该程序可使用虚函数相关的知识。

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<istream>
#include<iomanip>
#include<ostream>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<fstream>
#include<stack>
#include<ctime>
#include<deque>
#include<queue>
#include <sstream>
#include <numeric>
#pragma warning (disable:4996)

using namespace std;

const double PI = 3.14159265; 

class Shape { // 基类Shape
public:
    virtual double GetArea() const = 0; // 纯虚函数,用于计算面积
    virtual ~Shape() {}
};

class Rectangle : public Shape { // 矩形类
private:
    double length, width; // 长、宽
public:
    Rectangle(double l = 0, double w = 0) : length(l), width(w) {}
    double GetArea() const { return length * width; } // 计算面积
    ~Rectangle() {}
};

class Circle : public Shape { // 圆类
private:
    double radius; // 半径
public:
    Circle(double r = 0) : radius(r) {}
    double GetArea() const { return PI * radius * radius; } // 计算面积
    ~Circle() {} 
};

class Square : public Rectangle { // 正方形类,继承自矩形类
public:
    Square(double s) : Rectangle(s, s) {} 
    ~Square() {} 
};

int main() {
    Shape* s1 = new Circle(5); 
    cout << "The area of the Cirele is:" <<fixed<<setprecision(1)<< s1->GetArea() << endl;
    delete s1; 

    Shape* s2 = new Rectangle(4, 6); 
    cout << "The area of the Recanale is:" << fixed << setprecision(0)<< s2->GetArea() << endl;
    delete s2; 

    Shape* s3 = new Square(5);
    cout << "The area of the Recanale is:" << fixed << setprecision(0) << s3->GetArea() << endl;
    delete s3; 

    return 0;
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武帝为此

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值