0

I have matrix class and overloaded operator + working with other matrices and scalars. When I try to use it like mat2=mat+3; that works ok but if i change scalar and matrix mat2=3+mat; it says "Invalid operands to binary expression('int' and Matrix<3, 4>')" (3,4 is rows and columns in this matrix). How I understand I haven't overloaded + for this cases but I don't find how to overload it

Matrix operator+(const T &a) {
    Matrix<row, col, T> result;
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < col; ++j) {
            result.elements[i][j] = elements[i][j] + a;
        }

    }
    return result;
}

3 Answers3

2

That function is probably in your class. But how can you add an overload to int? Does int even have a class? Is it time to scream and panic?

Take a deep breath and look at the difference between global operator and member operator overloads. You can actually overload for int in the global scope, which will probably look like:

template <typename T>
Matrix<T> operator+(const T &a, Matrix<T> &m) { return m + a; }
scohe001
  • 15,110
  • 2
  • 31
  • 51
1

Suggestion: define operator+=() as member function of the class but define operator+() as a couple of external functions (friend to the class, if necessary). Maybe define the operator+() functions using the operator+=() method to avoid code duplication.

Something as (caution: code not tested and supposing Matrix has a copy constructor)

// method of the Matrix class
Matrix operator+= (T const & a)
 {
   for ( auto i = 0 ; i < row ; ++i )
      for ( auto j = 0 ; j < col ; ++j ) 
          elements[i][j] += a;

    return *this;
 }

// ordinary (external to the Matrix class) function
template <int row, int col, typename T>
Matrix<row, col, T> operator+ (Matrix<row, col, T> m, T const & a)
 { return m += a; }

// ordinary (external to the Matrix class) function
template <int row, int col, typename T>
Matrix<row, col, T> operator+ (T const & a, Matrix<row, col, T> m)
 { return m += a; }

Observe that both operator+() receive the Matrix value by copy.

max66
  • 65,235
  • 10
  • 71
  • 111
0

In order to be able to use

mat2=3+mat;

You have to overload the operator as a non-member function. Fortunately, its implementation is very simple.

template <typename T>
Matrix<T> operator+(const T &a, Matrix<T> const& mat) {
    return (mat + a);
}

Ideally, you should overload both versions as non-member functions.

template <typename T>
Matrix<T> operator+(Matrix<T> const& mat, const T &a ) {
   ...
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270