Jaydie
Jaydie

Reputation: 25

Multiple operands for overloaded * operator

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.

Upvotes: 1

Views: 231

Answers (1)

juanchopanza
juanchopanza

Reputation: 227458

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);

Upvotes: 3

Related Questions