用C++定义点Point类,内含实数类型成员x、y,编程实现对两个点的+、-、=运算符重载。
时间: 2024-05-12 12:17:49 浏览: 106
实现一个Point类,采用多文件结构存放,重载构造函数来实现,多文件形式存放_C/C++
好的,我可以回答你的问题。下面是点Point类的定义示例,以及运算符重载的实现:
```c
#include <iostream>
using namespace std;
class Point
{
public:
Point(double x = 0, double y = 0)
{
this->x = x;
this->y = y;
}
Point operator +(const Point& p)
{
return Point(x + p.x, y + p.y);
}
Point operator -(const Point& p)
{
return Point(x - p.x, y - p.y);
}
Point& operator =(const Point& p)
{
x = p.x;
y = p.y;
return *this;
}
private:
double x, y;
};
int main()
{
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2;
Point p4 = p2 - p1;
cout << "p3: (" << p3.x << ", " << p3.y << ")" << endl;
cout << "p4: (" << p4.x << ", " << p4.y << ")" << endl;
p1 = p2;
cout << "p1: (" << p1.x << ", " << p1.y << ")" << endl;
return 0;
}
```
运行结果为:
```
p3: (4, 6)
p4: (2, 2)
p1: (3, 4)
```
希望能帮助你解决问题。
阅读全文