【问题标题】:c++ overloading operators and constc++ 重载运算符和 const
【发布时间】:2012-12-14 19:10:03
【问题描述】:

以下代码返回此错误:

main.cpp|80|error: 将‘const matrix’作为‘this’参数传递 'T& 矩阵::at(size_t, size_t) [with T = int, size_t = long unsigned 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

【问题讨论】:

  • 我认为你的 *= 和 += 需要返回“matrix&”。顺便说一句。

标签: c++ templates operator-overloading


【解决方案1】:

您还需要为const matrix&lt;&gt; 重载at

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

【讨论】:

  • 哦,我忽略了这一点。 谢谢。下次我会在发布问题之前等待。
【解决方案2】:

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

如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 2014-08-16
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多