*运算符重载的操作数顺序 [英] operand order in * operator overload
问题描述
我为我的游戏物理引擎写了一个vec3类。
我做了一个运算符重载,允许我把一个向量乘以一个标量缩放向量):
const vec3运算符*(const real n)const
{
return vec3 (
m_x * n,
m_y * n,
m_z * n
);
}
这可以正常工作,如果我的计算顺序:
float rImpulse;
vec3 vContactNormal;
...
vec3 vImpulse = vContactNormal * rImpulse;
如果我改变乘法的顺序(例如,如果我把标量放在计算中)编译器不喜欢这个,并突出它作为一个错误。
我可以更新我的vec3类,所以乘法的顺序没有关系吗?怎么样?
(当我看到答案时,我可能会拍下我的额头。)
更新
我从vec3类中删除了原来的运算符重载,并在vec3类之外放置了以下两个运算符重载:
const vec3 operator *(const vec3& v,const real r)
{
return vec3(
vx()* r,
vy r,
vz()* r
);
}
const vec3 operator *(const real n,const vec3& v)
{
return v * n;
}
运算符,在类外(或在内部,作为朋友
):
const vec3 operator *(const real n,vec3 v)
{
//无需重新实现,因为你已经定义了v * n
return v * n;
}
原因是,当声明为类成员时,隐含地 this
,所以你基本上定义了 vec3 * real
。
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;
}
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
.
这篇关于*运算符重载的操作数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!