Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading * operator to work on both right and left

I have created a class Matrix which basically represents a mathematical matrix. In order to use a scalar-matrix multiplication, I have overloaded the * operator as:

Matrix Matrix::operator*(double scalar) const
{
    Matrix result(*this);
    result *= scalar;
    return result;
}

To make the operator work from left as well, I have used:

Matrix operator*(double a, const Matrix &M)
{
  return M * a;
}

Given Matrix M and double s, M * s works fine but s * M gives me an error:

Error C2677: binary * : no global operator found which takes type Matrix (or there is no acceptable conversion)

while the IDE shows me the error: "no operator * matches these operands".

Any idea what could be the problem?


Edit: That was a stupid mistake! I hadn't declared the operator in the header and the compiler couldn't see the declaration! So sorry for that...

like image 688
Alborz Avatar asked Jun 19 '13 18:06

Alborz


1 Answers

When I follow the recommendations given in the FAQ entry on operator overloading (especially the paragraph on binary arithmetic operators) I can not reproduce your error.

This compiles just fine for me:

struct M {
    M& operator*= (float f) {
        // multiply this by f
        return *this;
    }
};

inline M operator* (M m, float f) {
    m *= f;
    return m;
}

inline M operator* (float f, M m) {
    return m * f;
}

int main() {
    M m;
    float f;
    m * f;
    f * m;
}

I hope this helps. If not, please provide more code.

like image 72
moooeeeep Avatar answered Oct 04 '22 03:10

moooeeeep