#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;
}
202400905多态继承实例
最新推荐文章于 2024-10-09 10:07:13 发布