123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include <iostream>
- using namespace std;
- const double PI = 3.1416;
- class Box // 正方形类
- {
- private:
- double side;
- public:
- Box(double s) : side(s) {}
- double getArea()
- {
- return side * side;
- }
- double getPerimeter()
- {
- return 4 * side;
- }
- void set(double s)
- {
- side = s;
- }
- };
- class circle // 圆类
- {
- private:
- double radius;
- public:
- circle(double r) : radius(r) {}
- double getArea()
- {
- return PI * radius * radius;
- }
- double getPerimeter()
- {
- return 2 * PI * radius;
- }
- void set(double r)
- {
- radius = r;
- }
- };
- class NewStyle // 组合类
- {
- private:
- circle circleObj;
- Box boxObj;
- public:
- NewStyle(circle c, Box b) : circleObj(c), boxObj(b) {}
- double S()
- {
- return circleObj.getArea() - boxObj.getArea();
- }
- double L()
- {
- return circleObj.getPerimeter() + boxObj.getPerimeter();
- }
- void set(circle c, Box b)
- {
- circleObj = c;
- boxObj = b;
- }
- };
- int main()
- {
- circle A(4); // 圆的半径为4
- Box B(1); // 正方形的边长为1
- NewStyle C(A, B);
- cout << "自定义图形的面积: " << C.S() << endl;
- cout << "自定义图形的周长: " << C.L() << endl;
- A.set(6); // 圆的半径变为6
- B.set(2); // 正方形的边长变为2
- C.set(A, B);
- cout << "自定义图形的面积: " << C.S() << endl;
- cout << "自定义图形的周长: " << C.L() << endl;
- return 0;
- }
|