0

Currently, the code uses a member function operator + overload like this

Matrix operator + (const Matrix& B){
    int l = (int)B.a.size();
    int b = (int)B.a[0].size();
    for (int i = 0; i < l; i++){
        for (int j = 0; j < b; j++){
            this->a[i][j] = this->a[i][j] + B.a[i][j];
        }
    }
    return *this;
    }

Calling the + operator overload looks like

Matrix x;
Matrix y;
Matrix result;
result = x + y;

The code alters x also because we use this->a[i][j] = this->a[i][j] + b.a[i][j] the x gets updated to become result. How do I keep x constant and add the sum of x,y and put it into result?

Abhi
  • 1
  • 1
    How bout... not altering the content of `this`? You can typically just implement `+` with `+=`. – Passer By Mar 20 '22 at 14:29
  • 1
    `auto tmp = *this;`, use `tmp` in for-loop, then return `tmp`; – 康桓瑋 Mar 20 '22 at 14:31
  • (1) Make the member `const` i.e. `Matrix operator + (const Matrix& B) const`. This will *prevent* changing `x` in the expression `x+y`. It will also cause assignment to `this->a[i][j]` within the operator implementation to be a diagnosable error (unless `a` is marked `mutable` which it normally shouldn't be). (2) In the implementation of the `operator+()`, create another object of type `Matrix`, such as `Matrix result`, assign to elements of `result`, and return `result` rather than `*this`. – Peter Mar 20 '22 at 14:34
  • Perferrably implement this at namespace scope. This would allow you to use a argument implicitly convertible to a matrix as first parameter too(but you may want to add overloads where one of the parameters is an rvalue reference reuse memory, if possible... – fabian Mar 20 '22 at 14:34

0 Answers0