计算由圆和正方形构成的阴影部分的面积.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <iostream>
  2. using namespace std;
  3. const double PI = 3.1416;
  4. class Box // 正方形类
  5. {
  6. private:
  7. double side;
  8. public:
  9. Box(double s) : side(s) {}
  10. double getArea()
  11. {
  12. return side * side;
  13. }
  14. double getPerimeter()
  15. {
  16. return 4 * side;
  17. }
  18. void set(double s)
  19. {
  20. side = s;
  21. }
  22. };
  23. class circle // 圆类
  24. {
  25. private:
  26. double radius;
  27. public:
  28. circle(double r) : radius(r) {}
  29. double getArea()
  30. {
  31. return PI * radius * radius;
  32. }
  33. double getPerimeter()
  34. {
  35. return 2 * PI * radius;
  36. }
  37. void set(double r)
  38. {
  39. radius = r;
  40. }
  41. };
  42. class NewStyle // 组合类
  43. {
  44. private:
  45. circle circleObj;
  46. Box boxObj;
  47. public:
  48. NewStyle(circle c, Box b) : circleObj(c), boxObj(b) {}
  49. double S()
  50. {
  51. return circleObj.getArea() - boxObj.getArea();
  52. }
  53. double L()
  54. {
  55. return circleObj.getPerimeter() + boxObj.getPerimeter();
  56. }
  57. void set(circle c, Box b)
  58. {
  59. circleObj = c;
  60. boxObj = b;
  61. }
  62. };
  63. int main()
  64. {
  65. circle A(4); // 圆的半径为4
  66. Box B(1); // 正方形的边长为1
  67. NewStyle C(A, B);
  68. cout << "自定义图形的面积: " << C.S() << endl;
  69. cout << "自定义图形的周长: " << C.L() << endl;
  70. A.set(6); // 圆的半径变为6
  71. B.set(2); // 正方形的边长变为2
  72. C.set(A, B);
  73. cout << "自定义图形的面积: " << C.S() << endl;
  74. cout << "自定义图形的周长: " << C.L() << endl;
  75. return 0;
  76. }