Как перегрузить оператор +=?
Проблема заключается в том, что значение C остается тем же самым
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Number {
private:
int value;
public:
Number(int num) {
this->value = num;
}
int Value() const {
return value;
}
Number operator+(const Number& other) const {
Number new_num(this->value + other.Value());
return new_num;
}
Number operator-(const Number& other) const {
Number new_num(this->value - other.Value());
return new_num;
}
Number operator+=(const Number& other) const {
this->value = this->value + other.Value();
Number new_num(this->value);
return new_num;
}
};
int main() {
Number a(10);
Number b(15);
Number c = a + b;
std::cout << c.Value(); // 25
c += Number(100);
std::cout << c.Value(); // 125
std::cout << c.Value(); // 125
}
Ответы (1 шт):
Автор решения: Harry
→ Ссылка
Если вам нужна обычная семантика этого оператора, то как он может быть константным, если он меняет объект, к которому применен?!
Да и возвращайте просто сам этот объект, чтоб можно было cтроить цепочки операторов...
Number& operator+=(const Number& other) {
this->value += other.Value();
return *this;
}