图形抽象类的派生

 

【问题描述】抽象类Shape类,派生了Circle类和Rectangle类,请阅读主函数代码,完成Shape类、Circle类、Rectangle类的定义

【样例输入】无

【样例输出】

Rectangle: Width=3.5,Height=7.2

Area=25.2 Perimeter=21.4

Circle: R=2.3

Area=16.619 Perimeter=14.4513

Circle: R=1.5

Area=7.06858 Perimeter=9.42477

Rectangle: Width=3.5,Height=7.2

Area=25.2 Perimeter=21.4

#include <iostream>
#include <cmath>
#define PI 3.14159s
using namespace std;

// 抽象基类 Shape
class Shape {
public:
    // 纯虚函数
    virtual void print() const = 0;
    virtual double getArea() const = 0;
    virtual double getPerimeter() const = 0;
    // 虚析构函数(可选,但通常用于抽象基类)
    virtual ~Shape() {}
};

// Circle 类
class Circle: public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}

    void print() const  {
        cout << "Circle: R=" << radius << endl;
    }

    double getArea() const  {
        return PI * radius * radius;
    }

    double getPerimeter() const  {
        return 2 * PI * radius;
    }
};

// Rectangle 类
class Rectangle: public Shape {
private:
    double height, width;
public:
    Rectangle(double h, double w) :  height(h), width(w){}

    void print() const  {
        cout << "Rectangle: Width=" << width << ",Height=" << height << endl;
    }

    double getArea() const  {
        return width * height;
    }

    double getPerimeter() const  {
        return 2 * (width + height);
    }
};

int main() {
    Rectangle recA(7.2, 3.5), recB(7.2, 3.5);
    Circle circleA(2.3), circleB(1.5);
    Shape *pShape[4] = {&recB, &circleA, &circleB, &recA};
    for (int i = 0; i < 4; i++) {
        pShape[i]->print();
        cout << "Area=" << pShape[i]->getArea() << " Perimeter=" << pShape[i]->getPerimeter() << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值