Mar*_*sne 0 c++ compiler-construction overloading
我写了一个小的3d矢量类.特别是我写了两个函数,一个用于旋转向量,另一个用于返回向量本身的旋转副本.所以我有以下内容:
Vector Vector::Rotate(const double angle, Vector& axis) const {
Vector b=*this;
b.Rotate(angle,axis);
return (b);
}
void Vector::Rotate(const double angle, Vector & axis) {
/* let's promote this vector to a quaternion */
Quaternion V (0,*this);
/* quaternion describing the rotation */
Quaternion q (cos(angle/2),axis*sin(angle/2));
/* actual rotation */
*this = (q*V*q.conjugate()).Vec();
}
Run Code Online (Sandbox Code Playgroud)
现在,当我写这样的东西时:
vector2 = vector1.Rotate(rbo::M_PUCKER,i);
Run Code Online (Sandbox Code Playgroud)
我得到错误:没有运算符"="匹配这些操作数操作数类型是:Vector = void
我希望编译器能够理解我想要的东西:他为什么选择void版本而不是另一个返回向量?而且,按照我的方式编写更多相同功能的版本是一种很好的做法吗?
编译器仅根据调用成员函数的对象来选择const或不const重载.如果对象(或参考)是const它将选择const过载.
这是好习惯吗?不会.因为您对编译器应该做什么感到困惑,这似乎很明显.编写可以轻松阅读和解释而无混淆的代码通常是一种很好的做法:)