(1)声明Point(点)类,由Point类派生出Circle(圆)类,再由Circle类派生出Cylinder(圆柱体)类。将类的定义部分分别作为3个头文件,对它们的成员函数的声明部分分别作为3个源文件(.cpp文件),在主函数中用#include命令把它们包含进来,形
时间: 2024-02-27 12:58:50 浏览: 63
Point.h头文件定义:
```cpp
#ifndef POINT_H
#define POINT_H
class Point {
public:
Point(double x = 0, double y = 0);
double getX() const;
double getY() const;
void setX(double x);
void setY(double y);
private:
double x;
double y;
};
#endif
```
Point.cpp源文件实现:
```cpp
#include "Point.h"
Point::Point(double x, double y) {
this->x = x;
this->y = y;
}
double Point::getX() const {
return x;
}
double Point::getY() const {
return y;
}
void Point::setX(double x) {
this->x = x;
}
void Point::setY(double y) {
this->y = y;
}
```
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;
void setR(double r);
double area() const;
private:
double r;
};
#endif
```
Circle.cpp源文件实现:
```cpp
#include "Circle.h"
#include <cmath>
Circle::Circle(double x, double y, double r) : Point(x, y) {
this->r = r;
}
double Circle::getR() const {
return r;
}
void Circle::setR(double r) {
this->r = r;
}
double Circle::area() const {
return M_PI * r * r;
}
```
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;
void setH(double h);
double volume() const;
private:
double h;
};
#endif
```
Cylinder.cpp源文件实现:
```cpp
#include "Cylinder.h"
#include <cmath>
Cylinder::Cylinder(double x, double y, double r, double h) : Circle(x, y, r) {
this->h = h;
}
double Cylinder::getH() const {
return h;
}
void Cylinder::setH(double h) {
this->h = h;
}
double Cylinder::volume() const {
return area() * h;
}
```
主函数中的头文件包含:
```cpp
#include "Point.h"
#include "Circle.h"
#include "Cylinder.h"
```
阅读全文