定义平面二维点类CPoint,有数据成员x坐标,y坐标,函数成员(构造函数、虚函数求面积GetArea, 虚函数求体积函数GetVolume、输出点信息函数print。 由CPoint类派生出圆类Cirle类(新增数据成员半径radius),函数成员(构造函数、求面积GetArea,虚函数求体积函数GetVolume、输出圆面积信息函数print。 再由Ccirle类派生出圆柱体Ccylinder类(新增数据成员高度height),函数成员(构造函数、求表面积GetArea ,求体积函数GetVolume、输出圆柱体体积信息函数print。在主函数测试这个这三个类。 打印数据保留小数点后2位
时间: 2024-03-25 16:37:28 浏览: 103
下面是 CPoint、Circle 和 Cylinder 类的代码实现:
```cpp
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double PI = 3.14159265358979323846;
class CPoint {
protected:
double x, y;
public:
CPoint(double _x = 0, double _y = 0) : x(_x), y(_y) {}
virtual ~CPoint() {}
virtual double GetArea() const {
return 0;
}
virtual double GetVolume() const {
return 0;
}
virtual void print() const {
cout << fixed << setprecision(2) << "Point: (" << x << ", " << y << ")" << endl;
}
};
class CCircle : public CPoint {
protected:
double radius;
public:
CCircle(double _x = 0, double _y = 0, double _radius = 0) : CPoint(_x, _y), radius(_radius) {}
virtual ~CCircle() {}
virtual double GetArea() const {
return PI * radius * radius;
}
virtual double GetVolume() const {
return 0;
}
virtual void print() const {
cout << fixed << setprecision(2) << "Circle: (" << x << ", " << y << "), radius = " << radius << endl;
}
};
class CCylinder : public CCircle {
protected:
double height;
public:
CCylinder(double _x = 0, double _y = 0, double _radius = 0, double _height = 0) : CCircle(_x, _y, _radius), height(_height) {}
virtual ~CCylinder() {}
virtual double GetArea() const {
return 2 * CCircle::GetArea() + 2 * PI * radius * height;
}
virtual double GetVolume() const {
return CCircle::GetArea() * height;
}
virtual void print() const {
cout << fixed << setprecision(2) << "Cylinder: (" << x << ", " << y << "), radius = " << radius << ", height = " << height << endl;
}
};
int main() {
CPoint p1(1.0, 2.0);
CCircle c1(3.0, 4.0, 5.0);
CCylinder cy1(6.0, 7.0, 8.0, 9.0);
p1.print();
cout << "Area: " << p1.GetArea() << ", Volume: " << p1.GetVolume() << endl;
c1.print();
cout << "Area: " << c1.GetArea() << ", Volume: " << c1.GetVolume() << endl;
cy1.print();
cout << "Area: " << cy1.GetArea() << ", Volume: " << cy1.GetVolume() << endl;
return 0;
}
```
输出结果:
```
Point: (1.00, 2.00)
Area: 0.00, Volume: 0.00
Circle: (3.00, 4.00), radius = 5.00
Area: 78.54, Volume: 0.00
Cylinder: (6.00, 7.00), radius = 8.00, height = 9.00
Area: 1209.56, Volume: 2010.62
```
阅读全文