首先构建一个Point(点)类,包含数据成员x、y(坐标点)。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径),再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)。并且重载运算符“<<”,使之能用于输出Cylinder类的对象。最后在主函数中实例化Cylinder类,并通过cout显示。
时间: 2023-11-28 20:50:52 浏览: 53
下面是代码实现:
```c++
#include<iostream>
using namespace std;
class Point{ // 基类Point
public:
int x, y;
};
class Circle: public Point{ // 派生类Circle
public:
int r;
};
class Cylinder: public Circle{ // 派生类Cylinder
public:
int h;
friend ostream& operator<<(ostream& os, const Cylinder& cy){
os << "圆柱体的底部中心坐标为 (" << cy.x << ", " << cy.y << "), 半径为 " << cy.r << ", 高为 " << cy.h << endl;
return os;
}
};
int main(){
Cylinder cy;
cy.x = 0;
cy.y = 0;
cy.r = 3;
cy.h = 5;
cout << cy; // 输出圆柱体信息
return 0;
}
```
输出结果为:
```
圆柱体的底部中心坐标为 (0, 0), 半径为 3, 高为 5
```
相关问题
定义一个基类:点类,包括x坐标和y坐标,从它派生一个圆类,增加数据成员r(半径),
点类是一个基类,包括x坐标和y坐标这两个数据成员。可以通过定义构造函数和成员函数获取和修改这些数据成员的值。
圆类是从点类派生的子类,额外增加了一个数据成员r,表示圆的半径。同样也可以通过定义构造函数和成员函数获取和修改半径的值。
下面是一个简单的实例代码:
```cpp
class Point {
protected:
int x; // x坐标
int y; // y坐标
public:
Point(int x = 0, int y = 0) {
this->x = x;
this->y = y;
}
int getX() const {
return x;
}
int getY() const {
return y;
}
void setX(int x) {
this->x = x;
}
void setY(int y) {
this->y = y;
}
};
class Circle : public Point {
private:
int r; // 半径
public:
Circle(int x = 0, int y = 0, int r = 0) : Point(x, y) {
this->r = r;
}
int getR() const {
return r;
}
void setR(int r) {
this->r = r;
}
};
```
这样,我们可以通过实例化圆类的对象,并赋值x、y、r来表示一个圆的位置和半径。例如:
```cpp
int main() {
Circle c(5, 5, 10); // 实例化一个圆对象c,x=5,y=5,半径r=10
// 获取和修改坐标和半径
cout << "x坐标:" << c.getX() << endl;
cout << "y坐标:" << c.getY() << endl;
cout << "半径:" << c.getR() << endl;
c.setX(8);
cout << "修改后的x坐标:" << c.getX() << endl;
return 0;
}
```
以上输出结果为:
```
x坐标:5
y坐标:5
半径:10
修改后的x坐标:8
```
先建立一个点类point,包含数据成员x,y(坐标点)。以它为基类,派生出圆类circle,增加数据成员radius(半径),再以cirlcle类为直接基类,派生出圆柱体类cylinder,再增加数据
题目中先建立一个点类 Point,包含数据成员 x, y(坐标点)。以它为基类,派生出圆类 Circle,增加数据成员 radius(半径),再以 Circle 类为基类,派生出圆柱体类 Cylinder,增加数据成员 height(高),再增加数据成员 volume(体积)。