gpt4 book ai didi

C++ 常量规则?

转载 作者:行者123 更新时间:2023-11-30 02:10:41 25 4
gpt4 key购买 nike

我正在构建一个矩阵类来加强我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com