用C++ 三维坐标类Point有数据成员x、y、z。对象间操作时,需要通过函数成员重载“+”、前“——”、“==”操作符,通过友函数重载后“——”、“+=”、“>>”、“<<”操作符,实现三维坐标类对象间的直接操作。Main()完成了对象的定义和运算符重载函数的测试。
时间: 2023-11-05 07:51:28 浏览: 74
以下是三维坐标类Point的定义和运算符重载函数的实现:
```cpp
#include <iostream>
using namespace std;
class Point {
public:
double x, y, z;
Point() : x(0), y(0), z(0) {}
Point(double _x, double _y, double _z) : x(_x), y(_y), z(_z) {}
Point operator+(const Point& p) const {
return Point(x + p.x, y + p.y, z + p.z);
}
Point operator-() const {
return Point(-x, -y, -z);
}
bool operator==(const Point& p) const {
return x == p.x && y == p.y && z == p.z;
}
Point& operator+=(const Point& p) {
x += p.x;
y += p.y;
z += p.z;
return *this;
}
friend Point operator-(const Point& p1, const Point& p2) {
return Point(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z);
}
friend istream& operator>>(istream& in, Point& p) {
in >> p.x >> p.y >> p.z;
return in;
}
friend ostream& operator<<(ostream& out, const Point& p) {
out << "(" << p.x << ", " << p.y << ", " << p.z << ")";
return out;
}
};
int main() {
Point p1(1, 2, 3), p2(2, 3, 4);
cout << p1 << " + " << p2 << " = " << p1 + p2 << endl;
Point p3(1, 2, 3);
cout << "p3 = " << p3 << ", -p3 = " << -p3 << endl;
Point p4(1, 2, 3), p5(1, 2, 3), p6(2, 3, 4);
cout << "p4 == p5: " << (p4 == p5 ? "true" : "false") << endl;
cout << "p4 == p6: " << (p4 == p6 ? "true" : "false") << endl;
Point p7(1, 2, 3), p8(2, 3, 4);
p7 += p8;
cout << "p7 += " << p8 << ", p7 = " << p7 << endl;
Point p9(2, 3, 4), p10(1, 2, 3);
cout << p9 << " - " << p10 << " = " << p9 - p10 << endl;
Point p11;
cout << "Enter a point: ";
cin >> p11;
cout << "You entered " << p11 << endl;
return 0;
}
```
运行结果如下:
```
(1, 2, 3) + (2, 3, 4) = (3, 5, 7)
p3 = (1, 2, 3), -p3 = (-1, -2, -3)
p4 == p5: true
p4 == p6: false
p7 += (2, 3, 4), p7 = (3, 5, 7)
(2, 3, 4) - (1, 2, 3) = (1, 1, 1)
Enter a point: 1 2 3
You entered (1, 2, 3)
```
相关推荐
![cpp](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)