C++ 重载运算符和常量
c++ overloading operators and const
以下代码返回此错误:
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;
相关文章:
- 隐式常量/非常量运算符布尔
- 如何处理运算符=中的常量成员?
- 一种优雅或至少可行的方法,用于使用和接受具有重载方法和运算符的不同大小的文字数组常量
- 重载模板化类的[]运算符的常量版本
- 第二个常量在运算符函数中做什么?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 如何为句柄类提供运算符 -> 的常量版本
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 为什么类的赋值运算符的返回类型通常是非常量(而不是常量)引用?
- 引用模板类型的赋值运算符需要非常量重载
- 如何在 C++ 类中重载 'less than' 运算符以比较常量?
- 重载常量和非常量转换运算符返回数组类型时出现 MSVC 错误 C2593
- 为什么要在具有多个参数的重载运算符+中传递常量引用
- 字符和常量字符[2] 类型的操作数无效到二进制运算符
- 未找到采用常量类型的左操作数的'=='运算符
- C++ 重载运算符和常量
- 强制编译器选择常量运算符重载
- 当没有非常量运算符重载时,非常量对象将使用常量运算符
- 常量和非常量运算符重载
- std::string 的运算符 [] 和常量运算符 [] 之间的区别