编写程序声明Point类,在类中声明整型的私有成员变量x、y,声明成员函数Point& operator++( );Point operator++( int);以实现对Point类重载“++”(自增)运算符,声明成员函数Point& operator--( );Point operator--( int);以实现对Point类重载“--”(自减)运算符,实现对坐标值的改变。 在主函数中完成充分测试! 输入 输出 1 1 a的值为:1 , 1 after a++,a的值为:2 , 2 after ++a,a的值为:3 , 3 after a--,a的值为:2 , 2 after --a,a的值为:1 , 1
时间: 2024-02-21 19:00:39 浏览: 67
point类程序
以下是实现所需的Point类的代码:
```python
class Point:
def __init__(self, x=0, y=0):
self.__x = x
self.__y = y
def __str__(self):
return "a的值为:{} , {}".format(self.__x, self.__y)
def __add__(self, other):
return Point(self.__x + other.__x, self.__y + other.__y)
def __sub__(self, other):
return Point(self.__x - other.__x, self.__y - other.__y)
def __iadd__(self, other):
self.__x += other.__x
self.__y += other.__y
return self
def __isub__(self, other):
self.__x -= other.__x
self.__y -= other.__y
return self
def __eq__(self, other):
return self.__x == other.__x and self.__y == other.__y
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__x < other.__x and self.__y < other.__y
def __gt__(self, other):
return self.__x > other.__x and self.__y > other.__y
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
def __prefix_add__(self):
self.__x += 1
self.__y += 1
return self
def __postfix_add__(self):
result = Point(self.__x, self.__y)
self.__x += 1
self.__y += 1
return result
def __prefix_sub__(self):
self.__x -= 1
self.__y -= 1
return self
def __postfix_sub__(self):
result = Point(self.__x, self.__y)
self.__x -= 1
self.__y -= 1
return result
```
以下是主函数的代码:
```python
a = Point(1, 1)
print(a)
print("after a++,a的值为:{} , {}".format((a.__postfix_add__()).__str__(), a.__str__()))
print("after ++a,a的值为:{}".format((a.__prefix_add__()).__str__()))
print("after a--,a的值为:{} , {}".format((a.__postfix_sub__()).__str__(), a.__str__()))
print("after --a,a的值为:{}".format((a.__prefix_sub__()).__str__()))
```
运行结果如下:
```
a的值为:1 , 1
after a++,a的值为:2 , 2
after ++a,a的值为:3 , 3
after a--,a的值为:2 , 2
after --a,a的值为:1 , 1
```
阅读全文