定义基类Point(点)和派生类Circle(圆),求圆的周长。Point类有两个私有的数据成员float x,y;Circle类新增一个私有的数据成员半径float r和一个公有的求周长的函数getCircumference();主函数已经给出,请编写Point和Circle类。
#include <iostream>
#include<iomanip>
using namespace std;
//请编写你的代码
int main()
{
float x,y,r;
cin>>x>>y>>r;
Circle c(x,y,r);
cout<<fixed<<setprecision(2)<<c.getCircumference()<<endl;
return 0;
}
输入格式:
输入圆心和半径,x y r中间用空格分隔。
输出格式:
输出圆的周长,小数点后保留2位有效数字。
输入样例:
1 2 3
输出样例:
在这里给出相应的输出。例如:
Point constructor called
Circle constructor called
18.84
Circle destructor called
Point destructor called
#include <iostream>
#include <iomanip> // 包含输出流格式控制的库
using namespace std;
// 定义点类 Point
class Point {
float x, y; // 私有成员变量表示点的坐标
public:
// 构造函数,初始化点的坐标
Point(float x, float y) : x(x), y(y) {
cout << "Point constructor called" << endl; // 输出构造函数被调用的信息
}
// 析构函数,对象销毁时输出信息
~Point() {
cout << "Point destructor called" << endl; // 输出析构函数被调用的信息
}
};
// 定义圆类 Circle,公有继承自点类 Point
class Circle : public Point {
float r; // 圆的半径
public:
// 构造函数,初始化圆心坐标和半径
Circle(float x, float y, float r) : Point(x, y), r(r) {
cout << "Circle constructor called" << endl; // 输出构造函数被调用的信息
}
// 析构函数,对象销毁时输出信息
~Circle() {
cout << "Circle destructor called" << endl; // 输出析构函数被调用的信息
}
// 计算圆的周长
float getCircumference() {
return 2 * 3.14 * r; // 返回圆的周长
}
};
int main() {
float x, y, r; // 圆心坐标和半径
// 输入圆心坐标和半径
cin >> x >> y >> r;
// 创建 Circle 类的对象 c,调用构造函数初始化对象
Circle c(x, y, r);
// 输出圆的周长,设置小数点后两位输出
cout << fixed << setprecision(2) << c.getCircumference() << endl;
return 0;
}