编写程序,实现点(Point)-圆(Circle)-圆柱体(Cylinder)继承体系。要求如下: (1 Pin类包含x y坐标;(2)Circl类包括凰心和半径,能计算圆的面积;《3)Cyinder类包括府面圆和隔高,能计算体积;〈4)各类要实现怡当的的造函数;(5)利用主函数进行测试。
时间: 2024-02-25 15:54:33 浏览: 111
以下是实现了点(Point)-圆(Circle)-圆柱体(Cylinder)继承体系的程序:
```
#include <iostream>
#include <cmath>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double x=0, double y=0):x(x), y(y) {}
void setX(double x) {this->x = x;}
void setY(double y) {this->y = y;}
double getX() const {return x;}
double getY() const {return y;}
};
class Circle:public Point {
protected:
double r;
public:
Circle(double x=0, double y=0, double r=0):Point(x,y), r(r) {}
void setR(double r) {this->r = r;}
double getR() const {return r;}
double area() const {return M_PI * r * r;}
};
class Cylinder:public Circle {
private:
double h;
public:
Cylinder(double x=0, double y=0, double r=0, double h=0):Circle(x,y,r), h(h) {}
void setH(double h) {this->h = h;}
double getH() const {return h;}
double volume() const {return area() * h;}
};
int main() {
Point p(1,2);
Circle c(2,3,4);
Cylinder cy(3,4,5,6);
cout << "Point: (" << p.getX() << "," << p.getY() << ")" << endl;
cout << "Circle: (" << c.getX() << "," << c.getY() << "), r=" << c.getR() << ", area=" << c.area() << endl;
cout << "Cylinder: (" << cy.getX() << "," << cy.getY() << "), r=" << cy.getR() << ", h=" << cy.getH() << ", volume=" << cy.volume() << endl;
return 0;
}
```
在这个程序中,我们定义了三个类:Point、Circle 和 Cylinder。Point 类包含了 x 和 y 坐标;Circle 类包括圆心和半径,能计算圆的面积;Cylinder 类包括底面圆和隔高,能计算体积。各类都实现了构造函数,并且 Circle 和 Cylinder 类是通过继承 Point 类来实现的。
在主函数中,我们创建了一个 Point 类对象 p、一个 Circle 类对象 c 和一个 Cylinder 类对象 cy,并分别输出了它们的坐标、半径和高度等信息。
阅读全文