Manh Nguyen Huu
Manh Nguyen Huu

Reputation: 381

No operator = match these operands c++ even though said operator has been overloaded

I am trying to do a multiplication for my vector class and my matrix class.

Vector2f Matrix3x3::operator * (Vector2f & v) {
    float vx = e11 * v.x + e21 * v.y + e31;
    float vy = e12 * v.x + e22 * v.y + e32;
    return Vector2f(vx, vy);
}

When a matrix multiplies with a vector it should return a vector. So I try to set the result to an already created vector object.

Vector2f d(12, 12);
Matrix3x3 m = translationMatrix(transX, transY);
d = m * d;

VS keeps underlining my "=" and says that no operators = match these operands, operands type are Vector2f and Vector2f. Even though I already overload assignment operator in Vector2f class

Vector2f & Vector2f::operator = (Vector2f & V) { 
    x = V.x;
    y = V.y;
    return *this;
}

I dont even know where I am wrong. Can someone explain it to me?

Upvotes: 1

Views: 69

Answers (1)

songyuanyao
songyuanyao

Reputation: 173014

Matrix3x3::operator * returns by value, which means the object returned by m * d is a temporary, which can't be bound to lvalue-reference to non-const (i.e. Vector2f &); but it can be bound to lvalue-reference to const (i.e. const Vector2f &).

To solve the issue you chould change the parameter type of operator= to const Vector2f &, and you should do this also because the argument is supposed to be not modified inside operator=.

Vector2f & Vector2f::operator = (const Vector2f & V) { 
    x = V.x;
    y = V.y;
    return *this;
}

Upvotes: 4

Related Questions