c++ - 在 C++ 中重载 "+" orerator 时 that.vect.push_back(0) 和 that.vect.begin() 出错
问题描述
class Polinom {
public:
std::vector<double> vect;
Polinom operator +(const Polinom &that) {
if (this->vect.size() > that.vect.size()) {
for (int i = that.vect.size(); i < this->vect.size(); i++)
that.vect.push_back(0);//here
}
else if (that.vect.size() > this->vect.size()) {
for (int i = this->vect.size(); i < that.vect.size(); i++)
this->vect.push_back(0);
}
std::vector<double> sum;
std::vector<double>::iterator i2 = that.vect.begin();//here
for (std::vector<double>::iterator i1 = this->vect.begin(); i1 != this->vect.end(); ++i1)
sum.push_back(*i2++ + *i1);
return sum;
}
Polinom();
Polinom(std::vector<double> vect) {
this->vect = vect;
}
~Polinom();
};
严重性代码 描述 项目文件行抑制状态错误(活动) E1087 没有重载函数实例“std::vector<_Ty, _Alloc>::push_back [with _Ty=double, _Alloc=std::allocator]”与参数列表匹配并且对象(对象具有阻止匹配的类型限定符)
解决方案
Polinom operator +(const Polinom &that) { ^^^^^
that
是一个常量引用。
that.vect.push_back(0);//here
由于that
是 const,因此通过该引用的成员访问表达式也是如此。因此that.vect
是一个 const 表达式。
push_back
是一个非常量成员函数。它修改向量。该函数不能在 const 向量上调用。
std::vector<double>::iterator i2 = that.vect.begin();//here
std::vector<T>::begin() const
返回一个std::vector<T>::const_iterator
。它不能隐式转换为std::vector<T>::iterator
解决方案 1:不要尝试将元素推入 const 向量。
解决方案 2:当您打算修改引用的对象时,使用非常量引用。
在这种情况下,解决方案 1. 似乎更明智。修改 of 的操作数operator+
会违反直觉。this
此外,出于同样的原因,您可能应该使函数 const 合格,并避免修改。
推荐阅读
- python - 通过 sleep 模拟 django 视图的延迟
- spring-boot - 在本地环境中禁用 jms 侦听器
- r - 如何使用 OSX 命令行更改 R 中可用于数据存储设置的内存?
- c++ - 二维分拣卡算法
- php - 将目标空白添加到返回 $original_url
- twitter-bootstrap - Bootstrap 4如何根据数据属性值过滤列表
- c++11 - Dev-Cpp 5.11 是否支持 C++ 11?
- javascript - 如何在内容可编辑的 div 中编辑确切的元素?
- c++ - CMake check_function_exists 没有
- python - 使用 pip 在哪里放置用于安装的轮文件?