定义一个计数器Counter,包含私有变量,重载运算符“+,实现对象的相加c++”
时间: 2024-06-06 16:06:36 浏览: 82
运算符重载示例-面向对象程序设计
class Counter:
def __init__(self, count=0):
self._count = count
def __repr__(self):
return f'Counter(count={self._count})'
def __add__(self, other):
return Counter(self._count + other._count)
def __lt__(self, other):
return self._count < other._count
def __le__(self, other):
return self._count <= other._count
def __eq__(self, other):
return self._count == other._count
def __ne__(self, other):
return self._count != other._count
def __gt__(self, other):
return self._count > other._count
def __ge__(self, other):
return self._count >= other._count
def __str__(self):
return f'Counter: {self._count}'
c1 = Counter(5)
c2 = Counter(10)
c3 = c1 + c2
print(c1)
print(c2)
print(c3) # Counter: 15
阅读全文