使用继承实现点类、圆类、圆柱体类,并编写main()函数测试它们的功能。 要求每个类至少有数据初始化、输出功能, 圆类还具有面积计算、周长计算功能。 圆柱体类还具体面积计算、体积计算功能。
时间: 2023-06-26 08:05:08 浏览: 86
以下是实现点类、圆类、圆柱体类的代码:
```C++
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159265358979323846;
// 点类
class Point {
public:
Point(double x = 0, double y = 0) : x(x), y(y) {}
void set(double x, double y) {
this->x = x;
this->y = y;
}
void output() const {
cout << "(" << x << ", " << y << ")";
}
protected:
double x, y;
};
// 圆类
class Circle : public Point {
public:
Circle(double x = 0, double y = 0, double r = 0) : Point(x, y), r(r) {}
void set(double x, double y, double r) {
Point::set(x, y);
this->r = r;
}
double area() const {
return PI * r * r;
}
double perimeter() const {
return 2 * PI * r;
}
void output() const {
Point::output();
cout << " r = " << r;
}
protected:
double r;
};
// 圆柱体类
class Cylinder : public Circle {
public:
Cylinder(double x = 0, double y = 0, double r = 0, double h = 0) : Circle(x, y, r), h(h) {}
void set(double x, double y, double r, double h) {
Circle::set(x, y, r);
this->h = h;
}
double surface_area() const {
return 2 * PI * r * h + 2 * Circle::area();
}
double volume() const {
return Circle::area() * h;
}
void output() const {
Circle::output();
cout << " h = " << h;
}
protected:
double h;
};
int main() {
Point p(1, 2);
p.output(); // (1, 2)
Circle c(3, 4, 5);
c.output(); // (3, 4) r = 5
cout << " area = " << c.area() << " perimeter = " << c.perimeter() << endl;
Cylinder cy(6, 7, 8, 9);
cy.output(); // (6, 7) r = 8 h = 9
cout << " surface area = " << cy.surface_area() << " volume = " << cy.volume() << endl;
return 0;
}
```
输出结果:
```
(1, 2)
(3, 4) r = 5 area = 78.5398 perimeter = 31.4159
(6, 7) r = 8 h = 9 surface area = 1005.31 volume = 1809.56
```
阅读全文