空间一点p的坐标为(x,y,z),其中x,y,z为整数。编写点类Point3D,定义空间两点之间的加”+”,减”-”运算为相应三个坐标值分别进行加、减运算,要求实现空间两点之间的加”+”减”-”赋值”=”运算,空间两点间的比较”= =”运算。要求编写Point3D类的声明定义和测试程序。
时间: 2024-02-20 08:01:49 浏览: 14
好的,我知道了。以下是Point3D类的声明定义和测试程序:
```cpp
#include <iostream>
using namespace std;
class Point3D {
private:
int x, y, z;
public:
Point3D(int x = 0, int y = 0, int z = 0);
Point3D operator+(const Point3D& p) const;
Point3D operator-(const Point3D& p) const;
Point3D& operator=(const Point3D& p);
bool operator==(const Point3D& p) const;
friend ostream& operator<<(ostream& os, const Point3D& p);
};
Point3D::Point3D(int x, int y, int z) {
this->x = x;
this->y = y;
this->z = z;
}
Point3D Point3D::operator+(const Point3D& p) const {
return Point3D(x + p.x, y + p.y, z + p.z);
}
Point3D Point3D::operator-(const Point3D& p) const {
return Point3D(x - p.x, y - p.y, z - p.z);
}
Point3D& Point3D::operator=(const Point3D& p) {
x = p.x;
y = p.y;
z = p.z;
return *this;
}
bool Point3D::operator==(const Point3D& p) const {
return x == p.x && y == p.y && z == p.z;
}
ostream& operator<<(ostream& os, const Point3D& p) {
os << "(" << p.x << ", " << p.y << ", " << p.z << ")";
return os;
}
int main() {
Point3D p1(1, 2, 3);
Point3D p2(4, 5, 6);
Point3D p3 = p1 + p2;
Point3D p4 = p2 - p1;
cout << "p1 = " << p1 << endl;
cout << "p2 = " << p2 << endl;
cout << "p1 + p2 = " << p3 << endl;
cout << "p2 - p1 = " << p4 << endl;
if (p1 == p2) {
cout << "p1 == p2" << endl;
} else {
cout << "p1 != p2" << endl;
}
Point3D p5 = p1;
if (p1 == p5) {
cout << "p1 == p5" << endl;
} else {
cout << "p1 != p5" << endl;
}
return 0;
}
```
程序输出:
```
p1 = (1, 2, 3)
p2 = (4, 5, 6)
p1 + p2 = (5, 7, 9)
p2 - p1 = (3, 3, 3)
p1 != p2
p1 == p5
```
在测试程序中,我们首先定义了两个Point3D类型的点p1和p2,分别初始化为(1,2,3)和(4,5,6)。然后我们通过重载运算符+和-,实现了两个点之间的加、减运算。在测试程序中,我们分别用p3和p4记录了p1 + p2和p2 - p1的结果。接着,我们重载了赋值运算符=和比较运算符==,实现了点之间的赋值和比较操作。最后,我们对测试程序进行了输出,验证了我们实现的Point3D类的正确性。
相关推荐
![application/octet-stream](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)
![](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)