I have written a matrix class. I have overloaded the operator+, so that the user can write: matrix + 2. I would like the user to also write: 2 + matrix.
For the standard format (i.e. the object invoking 2) I have written a standard operator overloading function. It works.
template<typename T>
Matrix<T> Matrix<T>::operator+(const T& rhs) const
{
Matrix result(rows, cols, 0.0);
for (unsigned i = 0; i < rows; ++i)
{
for (unsigned j = 0; j < cols; ++j)
{
result(i,j) = (*this)(i, j) + rhs;
}
}
return result;
}
Now for the other order (i.e. 2 + matrix), I have written the friend function:
// Friend Functions that allow the user to write expressions in a different order
template<typename T>
friend Matrix<T> operator+(const T& type, const Matrix<T>& matrix);
and implementation as:
template<typename T>
Matrix<T> operator+(const T& type, const Matrix<T>& matrix)
{
return matrix + type;
}
When I try to write 2 + matrix (in main()), I get some errors.
I have always had problems using friend functions with generic classes and frankly, I have never understood why it never works for me.
Could someone please explain what I am doing wrong here?
Errors I get:
IntelliSense: no operator "+" matches these operands operand types are: int + Matrix
Severity Code Description Project File Line Error C2244 'Matrix::operator +': unable to match function definition to an existing declaration