在C ++中重载“ +”运算符时that.vect.push_back(0)和that.vect.begin()中的错误

Kru*_*get 4 c++ oop pointers vector

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();
};
Run Code Online (Sandbox Code Playgroud)

严重性代码说明项目文件行抑制状态错误(活动)E1087没有重载函数“ std :: vector <_Ty,_Alloc> :: push_back [with _Ty = double,_Alloc = std :: allocator]”的实例与参数列表匹配,并且对象(该对象具有阻止匹配的类型限定符)

eer*_*ika 7

Polinom operator +(const Polinom &that) {
                   ^^^^^
Run Code Online (Sandbox Code Playgroud)

that 是const引用。

that.vect.push_back(0);//here
Run Code Online (Sandbox Code Playgroud)

由于that是const,因此通过该引用的成员访问表达式也是如此。因此that.vect是一个const表达式。

push_back是一个非常量成员函数。它修改了向量。不能在const向量上调用该函数。

std::vector<double>::iterator i2 = that.vect.begin();//here
Run Code Online (Sandbox Code Playgroud)

std::vector<T>::begin() const返回std::vector<T>::const_iterator。它不能隐式转换为std::vector<T>::iterator

解决方案1:不要尝试将元素推入const向量。

解决方案2:当您打算修改引用的对象时,请使用非常量引用。

在这种情况下,解决方案1.似乎更明智。修改的操作数operator+会很直观。此外,this出于相同的原因,您可能应该使函数const合格,并避免修改。