定义Point(点)类,由Point类派生出Circle(圆)类,再由Circle类派生出Cylinder(圆柱体)类。将类的声明部分分别作为3个头文件,对它们的成员函数的定义部分分别作为3个源文件(.cpp文件),在主函数中用#include命令把它们包含进来,形成一个完整的程序,并上机运行。
时间: 2024-02-17 22:04:34 浏览: 122
好的,以下是Point类、Circle类和Cylinder类的声明部分:
Point.h
```cpp
#ifndef POINT_H
#define POINT_H
class Point {
public:
Point(double x = 0, double y = 0); // 构造函数
double getX() const; // 获取x坐标
double getY() const; // 获取y坐标
private:
double x, y; // 坐标
};
#endif
```
Circle.h
```cpp
#ifndef CIRCLE_H
#define CIRCLE_H
#include "Point.h"
class Circle : public Point {
public:
Circle(double x = 0, double y = 0, double r = 0); // 构造函数
double getR() const; // 获取半径
double getArea() const; // 获取面积
private:
double r; // 半径
};
#endif
```
Cylinder.h
```cpp
#ifndef CYLINDER_H
#define CYLINDER_H
#include "Circle.h"
class Cylinder : public Circle {
public:
Cylinder(double x = 0, double y = 0, double r = 0, double h = 0); // 构造函数
double getH() const; // 获取高度
double getVolume() const; // 获取体积
private:
double h; // 高度
};
#endif
```
接下来是Point类、Circle类和Cylinder类的定义部分:
Point.cpp
```cpp
#include "Point.h"
Point::Point(double x, double y) : x(x), y(y) {}
double Point::getX() const {
return x;
}
double Point::getY() const {
return y;
}
```
Circle.cpp
```cpp
#include "Circle.h"
#include <cmath>
Circle::Circle(double x, double y, double r) : Point(x, y), r(r) {}
double Circle::getR() const {
return r;
}
double Circle::getArea() const {
return M_PI * r * r;
}
```
Cylinder.cpp
```cpp
#include "Cylinder.h"
#include <cmath>
Cylinder::Cylinder(double x, double y, double r, double h) : Circle(x, y, r), h(h) {}
double Cylinder::getH() const {
return h;
}
double Cylinder::getVolume() const {
return getArea() * h;
}
```
最后是主函数:
main.cpp
```cpp
#include "Cylinder.h"
#include <iostream>
using namespace std;
int main() {
Cylinder cyl(1, 2, 3, 4);
cout << "圆柱体的底面圆的半径:" << cyl.getR() << endl;
cout << "圆柱体的高:" << cyl.getH() << endl;
cout << "圆柱体的体积:" << cyl.getVolume() << endl;
return 0;
}
```
编译链接后运行,输出结果为:
```
圆柱体的底面圆的半径:3
圆柱体的高:4
圆柱体的体积:113.097
```
阅读全文