添加代码重载+运算符实现两个计数器的相加 重载=运算符实现计数器的赋值
时间: 2024-03-22 14:41:16 浏览: 69
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter() : count(0) {}
Counter(int c) : count(c) {}
// 重载+运算符实现两个计数器的相加
Counter operator+(const Counter& c) const {
return Counter(count + c.count);
}
// 重载=运算符实现计数器的赋值
Counter& operator=(const Counter& c) {
count = c.count;
return *this;
}
void display() const {
cout << "Count: " << count << endl;
}
};
int main() {
Counter c1(5);
Counter c2(10);
Counter c3;
// 测试重载+运算符
c3 = c1 + c2;
cout << "c1 + c2 = ";
c3.display();
// 测试重载=运算符
c2 = c1;
cout << "c2 = ";
c2.display();
return 0;
}
```
运行结果:
```
c1 + c2 = Count: 15
c2 = Count: 5
```
阅读全文