开发者

C++ const rules?

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_matri开发者_运维问答x.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];
}


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.


template <class T, unsigned int rows, unsigned int cols>
T & Matrix<T,rows,cols>::operator()(int row, int col){
    return data[row][col];
}

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:

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];
}

(You will also have to declare the second version in the class body.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜