2.先建立一个Point(点)类,包含数据成员x,y(坐标点)。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径),再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,在增加数据成员h(高)。要求编写程序,重载运算符“<<”和“>>”,求解圆的面积和圆柱体
时间: 2024-02-04 10:04:00 浏览: 112
的体积,同时能够输入和输出圆和圆柱体对象的信息。
以下是基于您的要求编写的代码:
```c++
#include <iostream>
using namespace std;
const double PI = 3.14159265358979323846;
class Point {
public:
Point(double xx = 0, double yy = 0) : x(xx), y(yy) {}
friend istream& operator>>(istream& is, Point& p);
friend ostream& operator<<(ostream& os, const Point& p);
protected:
double x, y;
};
istream& operator>>(istream& is, Point& p) {
is >> p.x >> p.y;
return is;
}
ostream& operator<<(ostream& os, const Point& p) {
os << "(" << p.x << ", " << p.y << ")";
return os;
}
class Circle : public Point {
public:
Circle(double xx = 0, double yy = 0, double rr = 0) : Point(xx, yy), r(rr) {}
double area() const { return PI * r * r; }
friend istream& operator>>(istream& is, Circle& c);
friend ostream& operator<<(ostream& os, const Circle& c);
protected:
double r;
};
istream& operator>>(istream& is, Circle& c) {
is >> static_cast<Point&>(c) >> c.r;
return is;
}
ostream& operator<<(ostream& os, const Circle& c) {
os << "Center: " << static_cast<const Point&>(c) << ", Radius: " << c.r;
return os;
}
class Cylinder : public Circle {
public:
Cylinder(double xx = 0, double yy = 0, double rr = 0, double hh = 0) : Circle(xx, yy, rr), h(hh) {}
double volume() const { return Circle::area() * h; }
friend istream& operator>>(istream& is, Cylinder& cy);
friend ostream& operator<<(ostream& os, const Cylinder& cy);
protected:
double h;
};
istream& operator>>(istream& is, Cylinder& cy) {
is >> static_cast<Circle&>(cy) >> cy.h;
return is;
}
ostream& operator<<(ostream& os, const Cylinder& cy) {
os << "Base: " << static_cast<const Circle&>(cy) << ", Height: " << cy.h;
return os;
}
int main() {
Circle c(0, 0, 1);
cout << "Input circle info: ";
cin >> c;
cout << c << endl;
cout << "Circle area: " << c.area() << endl;
Cylinder cy(0, 0, 1, 2);
cout << "Input cylinder info: ";
cin >> cy;
cout << cy << endl;
cout << "Cylinder volume: " << cy.volume() << endl;
return 0;
}
```
在上面的代码中,Point类表示一个点,包含x和y坐标;Circle类继承自Point类,并增加了一个r成员表示半径,同时提供了计算面积的方法area();Cylinder类继承自Circle类,并增加了一个h成员表示高,同时提供了计算体积的方法volume()。重载运算符“<<”和“>>”用于输入和输出对象信息。在main函数中,先创建一个Circle对象和一个Cylinder对象,然后输入它们的信息并计算面积和体积,最后输出结果。
阅读全文