(1) 声明Point(点)类,由Point类派生出Circle(圆)类,再由Circle类派生出Cylinder(圆柱)类。将类的定义部分分别作为3个头文件。对它们的成员函数的声明部分分别作为3个源文件(.cpp文件),在主函数中用#include命令把它们包含进来。形成一个完整的程序,并上机运行。
时间: 2024-03-02 14:53:09 浏览: 59
关于多态性和虚函数应用的典型实例
好的,我明白你的问题了。下面是 Point 类的头文件定义(Point.h):
```cpp
#ifndef POINT_H
#define POINT_H
class Point {
public:
Point(double x = 0, double y = 0);
void setX(double x);
void setY(double y);
double getX() const;
double getY() const;
private:
double x;
double y;
};
#endif
```
下面是 Circle 类的头文件定义(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);
void setR(double r);
double getR() const;
double getArea() const;
private:
double r;
};
#endif
```
下面是 Cylinder 类的头文件定义(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);
void setH(double h);
double getH() const;
double getVolume() const;
private:
double h;
};
#endif
```
下面是 Point 类的实现部分(Point.cpp):
```cpp
#include "Point.h"
Point::Point(double x, double y) {
this->x = x;
this->y = y;
}
void Point::setX(double x) {
this->x = x;
}
void Point::setY(double y) {
this->y = y;
}
double Point::getX() const {
return x;
}
double Point::getY() const {
return y;
}
```
下面是 Circle 类的实现部分(Circle.cpp):
```cpp
#include "Circle.h"
#include <cmath>
Circle::Circle(double x, double y, double r) : Point(x, y) {
this->r = r;
}
void Circle::setR(double r) {
this->r = r;
}
double Circle::getR() const {
return r;
}
double Circle::getArea() const {
return M_PI * r * r;
}
```
下面是 Cylinder 类的实现部分(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;
}
void Cylinder::setH(double h) {
this->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 c(1, 2, 3, 4);
cout << "x = " << c.getX() << ", y = " << c.getY() << endl;
cout << "r = " << c.getR() << ", h = " << c.getH() << endl;
cout << "area = " << c.getArea() << ", volume = " << c.getVolume() << endl;
return 0;
}
```
注意:上述代码中的 `#ifndef`、`#define`、`#endif` 是为了防止头文件被重复包含。
阅读全文