C++常量规则?
我正在构建一个矩阵类来强化我的 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] != secondary_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];
}
I'm building a matrix class to reinforce my knowledge in c++. My overloaded == operator however keeps returning a 'discards qualifiers' error, which I understand to be a violation of the const rules somehow, but I can't figure out how.
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;
}
The error is returned on the 'if (data[i][j] != second_matrix(i,j))' line. So, just for completeness, here's my != operator:
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);
}
Also, the () operator:
template <class T, unsigned int rows, unsigned int cols>
T & Matrix<T,rows,cols>::operator()(int row, int col){
return data[row][col];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是你的 () 操作。它不是常量。您不能在 const 对象上调用非常量函数。制作 () 的 const 版本,通过 const& 返回。或按价值。
It's your () op. It isn't const. You can't call a non-const function on a const object. Make a const version of () that returns by const& or by value.
是非常量。这本身没问题,但对于只读访问,您需要重载此成员函数。然后,编译器将自动选择 const 重载:(
您还必须在类主体中声明第二个版本。)
Is non-const. This is fine by itself, but for read-only access you need to overload this member function. The compiler will then automatically pick the const overload:
(You will also have to declare the second version in the class body.)