首先构建一个Point(点)类,包含数据成员x、y(坐标点)。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径),再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)。并且重载运算符“<<”,使之能用于输出Cylinder类的对象。最后在主函数中实例化Cylinder类,并通过cout显示。c++
时间: 2023-11-28 22:50:45 浏览: 64
以下是代码实现:
```cpp
#include <iostream>
using namespace std;
class Point {
public:
Point(double xx = 0, double yy = 0) : x(xx), y(yy) {}
friend ostream& operator<<(ostream& os, const Point& p) {
os << "(" << p.x << "," << p.y << ")";
return os;
}
protected:
double x, y;
};
class Circle : public Point {
public:
Circle(double xx = 0, double yy = 0, double rr = 0) : Point(xx, yy), r(rr) {}
friend ostream& operator<<(ostream& os, const Circle& c) {
os << "Center: " << static_cast<Point>(c) << ", Radius: " << c.r;
return os;
}
protected:
double r;
};
class Cylinder : public Circle {
public:
Cylinder(double xx = 0, double yy = 0, double rr = 0, double hh = 0) : Circle(xx, yy, rr), h(hh) {}
friend ostream& operator<<(ostream& os, const Cylinder& cyl) {
os << "Base: " << static_cast<Circle>(cyl) << ", Height: " << cyl.h;
return os;
}
protected:
double h;
};
int main() {
Cylinder cyl(1, 2, 3, 4);
cout << cyl << endl;
return 0;
}
```
输出结果为:
```
Base: Center: (1,2), Radius: 3, Height: 4
```
阅读全文