1
votes

I want to overload the * operator for two purposes:

First purpose:

m4 * 3.5; //m4 is a matrix object

The above works with this function, absolutely no problem with the implementation here

Matrix operator *(const double n)

However, when I attempt the reverse, i.e

3.5 * m4;

I get an error saying there are no matching functions. So I made this function for this particular case

Matrix operator *(const double n, Matrix &obj)
{
    for(unsigned int i = 0; i < rows; i++ )
    {
        for(unsigned int j = 0; j < cols; j++)
        {
            obj[i][j] =  obj[i][j] * n;
        }

    }

    return *this;
}

Now, I get the error:

error: ‘Matrix Matrix::operator*(double, Matrix&)’ must take either zero or one argument Matrix operator *(const double n, Matrix &obj);

error: no match for ‘operator*’ (operand types are ‘double’ and ‘Matrix’)
cout << 3.5 * m4 << endl;

I am not sure how to overcome the problem of the operands!

Unfortunately I can't use BLAS, Eigen or the like. The assignment requires us to struggle through this matrix nonsense.

1
Please don't edit my post just to correct my grammar and incorrect capitalizations. I'm here for programming help not an English lesson. Those errors didn't hinder anyone's ability to understand my code! - Jaydie

1 Answers

3
votes

You have made Matrix operator *(const double n, Matrix &obj) a member of Matrix, which means it has an implicit first parameter for this. What you need to do is make it a non-member function.

Also note that it should not modify the operands, so you should pass the Matrix by const reference:

Matrix operator *(const double n, const Matrix &obj);

The same can be said for your first overload, which should either be a const member function

Matrix operator *(const double n) const;

or also a non member:

Matrix operator *(const Matrix& mat, const double n);