I'm writing a vec3 class for my game physics engine.
I've made an operator overload to allow me to multiply a vector by a scalar (to scale the vector):
const vec3 operator*( const real n ) const
{
return vec3(
m_x * n,
m_y * n,
m_z * n
);
}
This works correctly, if I use the correct order in my calculation:
float rImpulse;
vec3 vContactNormal;
...
vec3 vImpulse = vContactNormal * rImpulse;
if I change the order of multiplication (e.g. if I put the scalar first in the calculation), then compiler doesn't like this and highlights it as an error.
Can I update my vec3 class, so that order of multiplication doesn't matter? How? (I'll probably slap my forehead when I see the answer!)
Update
I've removed my original operator overload from the vec3 class and placed the following two operator overloads outside the vec3 class:
const vec3 operator*( const vec3 & v, const real r )
{
return vec3(
v.x() * r,
v.y() * r,
v.z() * r
);
}
const vec3 operator*( const real n, const vec3 & v )
{
return v * n;
}
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.
Math in C++ is very simple. Keep in mind that C++ mathematical operations follow a particular order much the same as high school math. For example, multiplication and division take precedence over addition and subtraction. The order in which these operations are evaluated can be changed using parentheses.
Overloading an operator cannot change its precedence.
The two member access operators, operator->() and operator->*() can be overloaded. The most common use of overloading these operators is with defining expression template classes, which is not a common programming technique.
You need to declare a free operator, outside the class (or inside, as a friend
):
const vec3 operator*( const real n, vec3 v )
{
//no need to re-implement, since you already have v * n defined
return v * n;
}
The reason is that, when declared as a class member, the first operator is implicitly this
, so you basically have defined vec3 * real
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With