首页 > 解决方案 > 在 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]”与参数列表匹配并且对象(对象具有阻止匹配的类型限定符)

标签: c++ooppointersvector

解决方案


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 合格,并避免修改。


推荐阅读