1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- #include <iostream>
- #include <iomanip>
- #include <cmath>
- // 基类 Shape
- class Shape {
- public:
- // 虚函数 GetArea,用于计算面积
- virtual double GetArea() const = 0;
- // 虚析构函数
- virtual ~Shape() {}
- };
- // 派生类 Rectangle
- class Rectangle : public Shape {
- protected:
- double length;
- double width;
- public:
- Rectangle(double l, double w) : length(l), width(w) {}
- // 实现 GetArea 函数
- double GetArea() const override {
- return length * width;
- }
- };
- // 派生类 Circle
- class Circle : public Shape {
- private:
- double radius;
- public:
- Circle(double r) : radius(r) {}
- // 实现 GetArea 函数
- double GetArea() const override {
- return M_PI * radius * radius;
- }
- };
- // 派生类 Square,继承自 Rectangle
- class Square : public Rectangle {
- public:
- Square(double side) : Rectangle(side, side) {}
- };
- int main() {
- // 动态生成半径为5的圆对象
- Shape* circle = new Circle(5);
- std::cout << std::fixed << std::setprecision(1);
- std::cout << "The area of the Cirele is:" << circle->GetArea() << std::endl;
- // 恢复默认格式
- std::cout.unsetf(std::ios::fixed);
- std::cout.precision(6);
- // 动态生成长为4,宽为6的矩形对象
- Shape* rectangle = new Rectangle(4, 6);
- std::cout << "The area of the Recanale is:" << rectangle->GetArea() << std::endl;
- // 动态生成边为5的正方形对象
- Shape* square = new Square(5);
- std::cout << "The area of the Recanale is:" << square->GetArea() << std::endl;
- // 释放动态分配的内存
- delete circle;
- delete rectangle;
- delete square;
- return 0;
- }
|