[英]How to call a non-const operator?
因此,在嘗試致電特定運營商時遇到了麻煩。 在某堂課上,我得到:
template <class Object>
const Object& MyVector<Object>::operator[] (int index ) const {
if (index < 0 || index >= mSize)
throw MyException();
return mObjects[index];
}
而且我也被給予
template <class Object>
Object& MyVector<Object>::operator[]( int index ){
if (index < 0 || index >= mSize)
throw MyException();
return mObjects[index];
}
我想調用第二個,以便可以修改該值,但是編譯器一直告訴我不能這樣做,因為我正在嘗試修改常量。
這是我嘗試使用運算符功能的地方:
template <class Object>
const Object& Matrix<Object>::get(int r, int c) const{
MyObject *row = & MyVectorObject[r]; //error
//snipped
}
我不斷收到錯誤:無法從const MyObject *
轉換為MyObject *
要調用對象的非常量成員函數(包括運算符),對象/引用必須為非常量。 如果通過指針調用該函數,則該函數必須是指向非常量的指針。
在您的情況下, MyVectorObject
是const,因此調用了const重載。 從代碼中看不出來為什么它是const,但是在注釋中卻表明它是成員。 通過this
指針隱式訪問成員,而在const成員函數內部, this
當然是指向const的指針。
Matrix<Object>::get()
方法是const,因此,如果您在該方法中訪問Matrix的類屬性,則所有這些屬性都將被視為const。
MyObject *row = & MyVectorObject[r]
將有效地調用const Object& MyVector<Object>::operator[] (int index ) const
。
const Object& MyVector<Object>::operator[] (int index ) const
將返回一個const Object&
。
因此, MyVectorObject[r]
的類型為const Object&
而& MyVectorObject[r]
的類型為const Object *
您應該這樣寫: const MyObject *row = & MyVectorObject[r];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.