2010-12-08 26 views
1

我正在構建一個矩陣類來加強我在C++中的知識。然而,我的重載==操作符不斷返回'丟棄限定符'錯誤,我知道這是違反const規則的方式,但我無法弄清楚。 'if(data [i] [j]!= second_matrix(i,j))''行返回錯誤。所以,只是爲了完整,這裏是我的=運算符:C++ const規則?

template <class T, unsigned int rows, unsigned int cols> 
bool Matrix<T,rows,cols>::operator!=(const Matrix<T,rows,cols>& second_matrix) const{ 
    return !(*this == second_matrix); 
} 

而且,()操作:

template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 

回答

3

這是你的()運算。這不是常量。你不能在const對象上調用非const函數。製作一個const版本的(),通過const &或按值返回。

+0

提示@JakeVA:原型`常量T&operator()的(INT行,int col)const;`。尾部的`const`意味着`* this`是const。 – ephemient 2010-12-08 06:43:02

1
template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 

是非常量。這本身就很好,但對於只讀訪問,您需要重載此成員函數。然後,編譯器會自動拾取常量過載:

template <class T, unsigned int rows, unsigned int cols> 
T & Matrix<T,rows,cols>::operator()(int row, int col){ 
    return data[row][col]; 
} 
template <class T, unsigned int rows, unsigned int cols> 
const T & Matrix<T,rows,cols>::operator()(int row, int col) const{ 
    return data[row][col]; 
} 

(你也必須申報在類體內的第二個版本。)