C++ 常量规则?

标签 c++ operator-overloading constants

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

相关文章:

c++ - Volatile 关键字允许访问 UnitTest++ 中的 const 结构

c++ - 接下来我应该学习哪种 C++ Material ?

c++ - 如何为 lambda 赋值重载 operator=?

c++ - 无法将 const 值发送到使用 operator[][] 的 operator+

c++ - 运算符重载使用operator +作为类模板

php - 可以将 Smarty 输出到 PHP 常量吗?

sql - 为整个数据库创建常量字符串

c++ - 临时对象: automatic,线程的存储时长是多少,是静态的还是动态的?

c++ - SDL_BlitSurface 分割错误

c++ - 为什么这个 write() 操作只写一行