首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++常量规则?

C++常量规则?
EN

Stack Overflow用户
提问于 2010-12-08 14:27:11
回答 2查看 405关注 0票数 1

我正在构建一个矩阵类来强化我在c++中的知识。然而,我的重载==操作符总是返回一个“放弃限定符”错误,我认为这在某种程度上违反了常量规则,但我不知道是怎么回事。

代码语言:javascript
复制
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 (datai != second_matrix(i,j))‘行返回错误。为了完整起见,下面是我的!=运算符:

代码语言:javascript
复制
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);
}

另外,()运算符:

代码语言:javascript
复制
template <class T, unsigned int rows, unsigned int cols>
T & Matrix<T,rows,cols>::operator()(int row, int col){
    return data[row][col];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-12-08 14:35:16

这是你的()行动。它不是const。不能在const对象上调用非常数函数。创建一个按const或值返回的const版本的()。

票数 3
EN

Stack Overflow用户

发布于 2010-12-08 19:41:50

代码语言:javascript
复制
template <class T, unsigned int rows, unsigned int cols>
T & Matrix<T,rows,cols>::operator()(int row, int col){
    return data[row][col];
}

是非常数。这本身就很好,但是对于只读访问,您需要重载这个成员函数。然后,编译器将自动选择const重载:

代码语言:javascript
复制
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];
}

(您还必须在类体中声明第二个版本。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4384755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档