几何图形的继承和派生.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. // 基类 Shape
  5. class Shape {
  6. public:
  7. // 虚函数 GetArea,用于计算面积
  8. virtual double GetArea() const = 0;
  9. // 虚析构函数
  10. virtual ~Shape() {}
  11. };
  12. // 派生类 Rectangle
  13. class Rectangle : public Shape {
  14. protected:
  15. double length;
  16. double width;
  17. public:
  18. Rectangle(double l, double w) : length(l), width(w) {}
  19. // 实现 GetArea 函数
  20. double GetArea() const override {
  21. return length * width;
  22. }
  23. };
  24. // 派生类 Circle
  25. class Circle : public Shape {
  26. private:
  27. double radius;
  28. public:
  29. Circle(double r) : radius(r) {}
  30. // 实现 GetArea 函数
  31. double GetArea() const override {
  32. return M_PI * radius * radius;
  33. }
  34. };
  35. // 派生类 Square,继承自 Rectangle
  36. class Square : public Rectangle {
  37. public:
  38. Square(double side) : Rectangle(side, side) {}
  39. };
  40. int main() {
  41. // 动态生成半径为5的圆对象
  42. Shape* circle = new Circle(5);
  43. std::cout << std::fixed << std::setprecision(1);
  44. std::cout << "The area of the Cirele is:" << circle->GetArea() << std::endl;
  45. // 恢复默认格式
  46. std::cout.unsetf(std::ios::fixed);
  47. std::cout.precision(6);
  48. // 动态生成长为4,宽为6的矩形对象
  49. Shape* rectangle = new Rectangle(4, 6);
  50. std::cout << "The area of the Recanale is:" << rectangle->GetArea() << std::endl;
  51. // 动态生成边为5的正方形对象
  52. Shape* square = new Square(5);
  53. std::cout << "The area of the Recanale is:" << square->GetArea() << std::endl;
  54. // 释放动态分配的内存
  55. delete circle;
  56. delete rectangle;
  57. delete square;
  58. return 0;
  59. }