#include <iostream>
#include <vector>
// 基类Shape
class Shape {
public:
// 纯虚函数计算面积
virtual double calculateArea() const = 0;
virtual ~Shape() = default;
};
// 派生类Circle
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const override {
return 3.14159 * radius * radius;
}
};
// 派生类Rectangle
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double calculateArea() const override {
return width * height;
}
};
int main() {
// 使用std::vector存储Shape指针
std::vector<Shape*> shapes;
// 创建Circle和Rectangle对象并添加到数组中
shapes.push_back(new Circle(5));
shapes.push_back(new Rectangle(4, 6));
double totalArea = 0;
// 遍历数组,调用calculateArea函数计算总面积
for (const auto& shape : shapes) {
totalArea += shape->calculateArea();
}
std::cout << "总面积: " << totalArea << std::endl;
// 释放内存
for (const auto& shape : shapes) {
delete shape;
}
return 0;
}
设计原则体现
- 封装:
Circle
和Rectangle
类将数据成员(如radius
、width
、height
)封装在类内部,通过成员函数来访问和操作这些数据,保证了数据的安全性。
Shape
类封装了公共的接口calculateArea
,使得派生类遵循统一的接口规范。
- 继承:
Circle
和Rectangle
类继承自Shape
类,继承了Shape
类的接口,同时可以根据自身的特性实现calculateArea
函数,实现了代码的复用和扩展。
- 多态:
- 通过
Shape
指针数组存储不同派生类对象的指针,在运行时根据实际对象的类型调用相应的calculateArea
函数,体现了多态性。这使得代码更加灵活,易于扩展新的形状类而不需要修改大量现有代码。