Const正确性和操作员*

时间:2012-01-20 17:40:36

标签: c++ const

我定义了这样一个类:

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;
}

3 个答案:

答案 0 :(得分:3)

如果你展示的代码是非const方法,那么this指针是非const的,非const conjugate方法当然比const方法更好地匹配。在超载决策中不考虑返回类型。如果您想坚持使用const版本,可以添加constness:resQ = vQ*(static_cast<const Quaternion*>(this)->conjugate());

答案 1 :(得分:0)

您使用this的方法可能是非常量的。

类型this的成员函数A的类型为A * const。对于const成员函数,它是const A * const

因此,如果您将代码输入const方法,您的代码将按预期执行。

如果你想强制调用const的函数重载,你需要做一个const-cast:

  const_cast<const Quaternion * const>(this)->conjugate();

答案 2 :(得分:0)

*这不是const(尽管它在const方法中使用),以及关于const重载的c++ FAQ Lite状态(在FAQ的下标运算符的情况下);

  

将下标运算符应用于MyFredList对象时   非const,编译器将调用非const下标运算符。

翻译,因为*这是非const,所以将调用非const方法。

相关问题