使用c++编写一个二维点和三维点类。 要求: (1)二维点类有x,y坐标属性,编写计算点到坐标原点距离函数; (2)三维点从二维点派生而来,编写计算点到坐标原点距离函数。
时间: 2024-02-24 10:59:33 浏览: 174
好的,下面是使用C++编写的二维点和三维点类:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 二维点类
class Point2D {
private:
double x, y;
public:
Point2D(double x, double y) {
this->x = x;
this->y = y;
}
double distance_to_origin() {
return sqrt(x * x + y * y);
}
};
// 三维点类
class Point3D : public Point2D {
private:
double z;
public:
Point3D(double x, double y, double z) : Point2D(x, y) {
this->z = z;
}
double distance_to_origin() {
return sqrt(x * x + y * y + z * z);
}
};
```
在二维点类中,我们定义了`x`和`y`两个私有属性,并且实现了计算点到坐标原点距离的函数`distance_to_origin`。在三维点类中,我们从二维点类派生而来,并且增加了`z`私有属性,并且重写了计算点到坐标原点距离的函数`distance_to_origin`。由于二维点类和三维点类都具有`distance_to_origin`函数,因此在使用时,会自动调用相应对象所属的类的函数。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)