我定义了这样一个类:
Quaternion& conjugate(); //negates the vector component of the quaternion
Quaternion conjugate() const; //same but in without modifying the class...
Quaternion& operator = (Quaternion const& Qrhs);
Quaternion& operator *= (Quaternion const& Q);
Quaternion operator * (Quaternion const& Qrhs) const;
现在我像这样使用这个函数:
PRINTVAR(*this); //this is the first time printed (a little macro to print line and file)
Quaternion vQ(0.,vn), resQ;
resQ = vQ*(this->conjugate()); //this is the method I want to discuss...
PRINTVAR(*this); //this is the second time
resQ = *this * resQ;
这是输出
*this: (0:0:0:0) at line: 128 in file: Quaternions.cpp
*this: (-0:-0:-0:0) at line: 131 in file: Quaternions.cpp
我认为通过在行 resQ = vQ*(this should be called as const)...
中调用运算符 *
为什么我再次打印 *this
会改变?
这里是共轭函数的定义:
Quaternion& Quaternion::conjugate(){
/* Given: Nothing
* Task: Invert sign of the vector
* Return: the class which will be modified
*/
V3 vec;
vec = -(this->getVector());
x() = vec[0];
y() = vec[1];
z() = vec[2];
return *this;
}
Quaternion Quaternion::conjugate() const{
Quaternion result(*this);
result.conjugate();
return result;
}
最佳答案
如果您显示的代码是在非常量方法中,那么 this
指针是非常量,非常量 conjugate
method 当然比 const 更好。重载决策中不考虑返回类型。如果想坚持使用const版本,可以加上constness: resQ = vQ*(static_cast<const Quaternion*>(this)->conjugate());
关于c++ - Const 正确性和运算符 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945560/