简体   繁体   English

C ++重载运算符和const

[英]c++ overloading operators and const

Following code return this error: 以下代码返回此错误:

main.cpp|80|error: passing 'const matrix' as 'this' argument of 'T& matrix::at(size_t, size_t) [with T = int, size_t = long unsigned int]' discards qualifiers [-fpermissive]' main.cpp | 80 |错误:将'const矩阵'作为'T&matrix :: at(size_t,size_t)的'this'参数传递[with T = int,size_t = long unsigned int]'丢弃限定符[-fpermissive]'

Any thoughts why and how to repair it? 有什么想法为什么以及如何修复它?

#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 http://ideone.com/5OigTP

You need to overload at for const matrix<> as well: 您还需要at const matrix<>重载:

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

have you tried adding a const overload for at() ??? 您是否尝试为at()添加const重载?

as in: 如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM