几何图形的继承和派生(有输入).cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4. #define pi 3.14
  5. class Shape {
  6. public:
  7. virtual double GetArea() const = 0;
  8. virtual ~Shape() {}
  9. };
  10. class Circle : public Shape {
  11. private:
  12. double radius;
  13. public:
  14. Circle(double r) : radius(r) {}
  15. double GetArea() const override {
  16. return pi * radius * radius;
  17. }
  18. };
  19. class Rectangle : public Shape {
  20. private:
  21. double length;
  22. double width;
  23. public:
  24. Rectangle(double l, double w) : length(l), width(w) {}
  25. double GetArea() const override {
  26. return length * width;
  27. }
  28. };
  29. class Square : public Rectangle {
  30. public:
  31. Square(double side) : Rectangle(side, side) {}
  32. };
  33. int main() {
  34. double radius;
  35. std::cin >> radius;
  36. Circle* circle = new Circle(radius);
  37. std::cout << "The area of the Cirele is:" << circle->GetArea() << std::endl;
  38. delete circle;
  39. double length, width;
  40. std::cin >> length >> width;
  41. Rectangle* rectangle = new Rectangle(length, width);
  42. std::cout << "The area of the Recanale is:" << rectangle->GetArea() << std::endl;
  43. delete rectangle;
  44. double side;
  45. std::cin >> side;
  46. Square* square = new Square(side);
  47. std::cout << "The area of the Recanale is:" << square->GetArea() << std::endl;
  48. delete square;
  49. return 0;
  50. }