-3

I have a vec2 class, defined like this

class vec2 { public: float x, y; ... //add a scalar vec2 operator+(float s) const { return vec2(this->x + s, this->y + s); } }; 

The operator+ overload works good when doing vec2 v = otherVector * 2.0f; but doesn't work when doing it backwards, like so vec2 v = 2.0f * otherVector;.

What's the solution to this?

0

1 Answer 1

0

Taking your example, the expression

otherVector * 2.0f 

is equivalent to

otherVector.operator+(2.0f) 

Creating an overloaded operator as a member function only allows the object to be on the left-hand side, and the right-hand side is passed to the function.

The simple solution is to add another operator overload, as a non-member function

vec2 operator+(float f, const vec2& v) { return v + f; // Use vec2::operator+ } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.