我正在构建一个矩阵类来加强我在 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{
if (_rows != second_matrix.getNumRows() || _cols != second_matrix.getNumCols())
return false;
else{
unsigned int i,j;
for (i = 0; i < rows; i++){
for (j = 0; j < cols; j++){
if (data[i][j] != second_matrix(i,j))
return false;
}
}
}
return true;
}
错误在“if (data[i][j] != second_matrix(i,j))”行返回。所以,为了完整起见,这是我的 != 运算符:
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];
}
最佳答案
这是您的 () 操作。它不是常量。您不能在 const 对象上调用非常量函数。制作一个 () 的 const 版本,它通过 const& 或按值返回。
关于C++ 常量规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384755/