用C++编写一个程序,声明一个Circle类,有数据成员Radius(半径)、成员函数GetArea(),并满足以下要求。 (1)需要定义和合理的构造函数。 (2)使用函数重载方式重载成员函数,当输入一个参数时,被认作创建圆,并认为输入圆半径,计算并返回圆的面积;当输入两个参数时,认为创建一个圆,计算并返回圆环的面积; (3)其他自行界定。 (4)编写合适的主函数,构造一个Circle的对象进行对象创建,以及成员函数的测试。 样例1: 【输入形式】10 【输出形式】 the circle is created! the area is:314
时间: 2024-03-24 21:37:27 浏览: 16
以下是实现要求的代码:
```cpp
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
Circle() {
cout << "a circle is created!" << endl;
radius = 0;
}
Circle(double r) {
cout << "a circle is created!" << endl;
radius = r;
}
double GetArea() {
return 3.14 * radius * radius;
}
double GetArea(double r1, double r2) {
Circle c1(r1);
Circle c2(r2);
double area = c1.GetArea() - c2.GetArea();
return area;
}
};
int main() {
double r1, r2;
cout << "Please input the radius of the circle:";
cin >> r1;
Circle c1(r1);
double area1 = c1.GetArea();
cout << "the area is:" << area1 << endl;
cout << "Please input the radius of the larger circle:";
cin >> r1;
cout << "Please input the radius of the smaller circle:";
cin >> r2;
double area2 = c1.GetArea(r1, r2);
cout << "the area of ring is:" << area2 << endl;
return 0;
}
```
当输入10时,输出结果为:
```
Please input the radius of the circle:10
a circle is created!
the area is:314
Please input the radius of the larger circle:10
Please input the radius of the smaller circle:5
a circle is created!
a circle is created!
the area of ring is:235.5
```