实现一个Point类,该类拥有私有数据成员x和y,要求用运算符重载的方式实现以下功能: 1)前缀自增(即把x和y的值均加1)。 2)大于运算(x * x + y * y的值大者为大)。 3)加法运算(两个点的加法为x和y对应相加)。 再写一段测试代码,测试类Point的功能。
时间: 2024-02-03 19:12:35 浏览: 27
以下是Point类的实现及测试代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int xx = 0, int yy = 0): x(xx), y(yy) {}
Point operator++(); //前缀自增
bool operator>(const Point& p); //大于运算
Point operator+(const Point& p); //加法运算
void print() { cout << "(" << x << ", " << y << ")"; }
};
Point Point::operator++() {
++x;
++y;
return *this;
}
bool Point::operator>(const Point& p) {
return (x*x + y*y) > (p.x*p.x + p.y*p.y);
}
Point Point::operator+(const Point& p) {
Point res(x + p.x, y + p.y);
return res;
}
int main() {
Point p1(1,2), p2(3,4);
p1.print(); //输出 (1, 2)
++p1;
p1.print(); //输出 (2, 3)
if (p1 > p2) {
cout << "p1 > p2" << endl; // 输出 p1 > p2
} else {
cout << "p1 <= p2" << endl;
}
Point p3 = p1 + p2;
p3.print(); //输出 (5, 7)
return 0;
}
```
注:以上代码为C++的实现方式,若需在其他编程语言中实现,请参照对应语言的运算符重载机制。