Как перегрузить оператор +=?

Рейтинг: 0Ответов: 1Опубликовано: 05.03.2023

Проблема заключается в том, что значение 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
}


Ответы

▲ 5Принят

Если вам нужна обычная семантика этого оператора, то как он может быть константным, если он меняет объект, к которому применен?!

Да и возвращайте просто сам этот объект, чтоб можно было cтроить цепочки операторов...

Number& operator+=(const Number& other) {
    this->value += other.Value();
    return *this;
}