202400905多态继承实例

#include <iostream>
#include <cmath>  // 用于 sqrt 函数
using namespace std;

// 图形基类
class Graphical {
protected:
    float perimeter;  // 周长
    float area;       // 面积

public:
    virtual float getPerimeter() const = 0;  // 获取周长的纯虚函数
    virtual float getArea() const = 0;       // 获取面积的纯虚函数
    virtual ~Graphical() {}  // 虚析构函数
};

// 矩形类
class Rectangle : public Graphical {
private:
    float length;  // 长
    float wide;    // 宽

public:
    // 构造函数
    Rectangle(float l, float w) : length(l), wide(w) {}

    // 重写获取周长函数
    float getPerimeter() const override {
        return 2 * (length + wide);
    }

    // 重写获取面积函数
    float getArea() const override {
        return length * wide;
    }
};

// 圆类
class Circle : public Graphical {
private:
    float radius;  // 半径

public:
    // 构造函数
    Circle(float r) : radius(r) {}

    // 重写获取周长函数
    float getPerimeter() const override {
        return 2 * M_PI * radius;  // M_PI 是圆周率常数
    }

    // 重写获取面积函数
    float getArea() const override {
        return M_PI * radius * radius;
    }
};

// 三角形类
class Triangle : public Graphical {
private:
    float a, b, c;  // 三条边

public:
    // 构造函数
    Triangle(float sideA, float sideB, float sideC) : a(sideA), b(sideB), c(sideC) {}

    // 重写获取周长函数
    float getPerimeter() const override {
        return a + b + c;
    }

    // 重写获取面积函数 (海伦公式)
    float getArea() const override {
        float p = (a + b + c) / 2;  // 计算半周长
        return sqrt(p * (p - a) * (p - b) * (p - c));  // 计算面积
    }
};

// 全局函数:输出图形的周长和面积
void printGraphicalProperties(const Graphical& g) {
    cout << "Perimeter: " << g.getPerimeter() << endl;
    cout << "Area: " << g.getArea() << endl;
}

int main() {
    // 创建矩形、圆和三角形对象
    Rectangle rect(5.0f, 3.0f);
    Circle circle(4.0f);
    Triangle triangle(3.0f, 4.0f, 5.0f);

    // 输出矩形的周长和面积
    cout << "Rectangle:" << endl;
    printGraphicalProperties(rect);

    // 输出圆的周长和面积
    cout << "Circle:" << endl;
    printGraphicalProperties(circle);

    // 输出三角形的周长和面积
    cout << "Triangle:" << endl;
    printGraphicalProperties(triangle);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值