C++ 重载运算符和常量

c++ overloading operators and const

本文关键字:常量 运算符 重载 C++      更新时间:2023-10-16

以下代码返回此错误:

main.cpp|80|error:将"const matrix"作为 'this' 参数传递 'T& matrix::at(size_t, size_t) [T = int, size_t = long 无符号 int]' 丢弃限定符 [-fpermissive]'

有什么想法为什么以及如何修复它吗?

#include <vector>
template <typename T>
class matrix
{
    std::vector< std::vector<T> > data;
    size_t N, M;    
public:
        T& at(size_t x, size_t y);
        matrix<T> operator+(const matrix<T>& m2) const;
};
template<class T>
T& matrix<T>::at(size_t x, size_t y)
{ return data[x][y]; }
template<class T>
matrix<T> matrix<T>::operator+(const matrix<T>& m2) const
{    
    matrix<T> res; //initialization of internals not related to error
    for(unsigned int i=0; i<N; ++i)
        for(unsigned int j=0; j<M; ++j)
            res.at(i,j) = this->at(i, j) + m2.at(i, j);    
    return res;
}
int main()
{
    matrix<int> a, b; //initialization of internals not related to error
    a = a + b;
    return 0;
}

http://ideone.com/5OigTP

还需要重载at以进行const matrix<>

template<class T>
const T& matrix<T>::at(size_t x, size_t y) const
{
    return data[x][y];
}

您是否尝试过为at() ???添加const重载

如:

const T& at(size_t x, size_t y) const;