Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. #define PI 3.14159265
  4.  
  5. using namespace std;
  6.  
  7. struct Coord {
  8. float x;
  9. float y;
  10. Coord() : x(0), y(0) {}
  11. };
  12.  
  13. class Shape {
  14. protected:
  15. Coord center;
  16.  
  17. public:
  18. /*Shape(){}*/
  19. virtual float area() = 0; // 面積 抽象類別
  20. virtual float perimeter() = 0; // 周長
  21.  
  22. void Set(float x, float y)
  23. {
  24. center.x = x;
  25. center.y = y;
  26. }
  27.  
  28. Coord GetCenter()
  29. {
  30. return center;
  31. }
  32.  
  33. const Coord & GetCenterRef()
  34. {
  35. return center;
  36. }
  37. };
  38.  
  39. class Reactangle : public Shape {
  40. public:
  41. float width;
  42. float height;
  43.  
  44. public:
  45. Reactangle(float w, float h) : /*Shape(),*/ width(w), height(h) // 不寫 Shape() 會自動呼叫父類別的 constructor
  46. {
  47. }
  48.  
  49. virtual float area()
  50. {
  51. return width * height;
  52. }
  53.  
  54. virtual float perimeter()
  55. {
  56. return width + width + height + height;
  57. }
  58.  
  59. };
  60.  
  61. class Square : public Reactangle {
  62. public:
  63. Square(float w) : Reactangle(w, w)
  64. {
  65. }
  66. };
  67.  
  68. class Circle : public Shape {
  69. public:
  70. float radius; // 半徑
  71.  
  72. public:
  73. Circle(float r) : radius(r)
  74. {
  75. }
  76.  
  77. float area()
  78. {
  79. return radius * radius * PI;
  80. }
  81.  
  82. float perimeter()
  83. {
  84. return (radius + radius) * PI;
  85. }
  86.  
  87. };
  88.  
  89. class Ellipse : public Shape {
  90. private:
  91. float height;
  92. float width;
  93.  
  94. public:
  95. Ellipse(float h, float w) : height(h), width(w)
  96. {
  97. }
  98.  
  99. float area() {
  100. return (height/2) * (width/2) * PI;
  101. }
  102.  
  103. float perimeter() {
  104. float res;
  105. res = (width > height) ? 2*PI*(height/2) + 4*(width-height) : 2*PI*(width/2) + 4*(height-width);
  106. return res;
  107. }
  108. };
  109.  
  110. ostream& operator << (ostream & out, Coord c)
  111. {
  112. out << "(" << c.x << "," << c.y << ")";
  113. return out;
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement