2012-01-20 47 views
0

我定義如下的類: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

如果顯示的代碼是在一個非const方法,比this指針非const和非const conjugate方法當然是比常規比賽更好的比賽。在超載決策中不考慮返回類型。如果你想堅持使用const版本,你可以添加常量:resQ = vQ*(static_cast<const Quaternion*>(this)->conjugate());

0

也許你使用的方法是this非const。

this類型A的成員函數的類型,是A * const。對於const成員函數,它是const A * const

因此,如果您將代碼輸入到const方法中,您的代碼將按照您的預期執行。

如果要強制調用的函數常量重載你需要做一個常量播:

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

*這不是常量(雖然它是在一個const方法使用),以及c++ FAQ Lite關於const重載(關於下標操作符的常見問題)的狀態;

當您將標運算符的MyFredList對象是 非const,編譯器會調用非const下標運算符。

翻譯,因爲*這是非const,非const方法將被調用。