Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in that.vect.push_back(0) and that.vect.begin() in overloading "+" orerator in C++

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();
};

Severity Code Description Project File Line Suppression State Error (active) E1087 no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=double, _Alloc=std::allocator]" matches the argument list and object (the object has type qualifiers that prevent a match)

like image 984
Pie Avatar asked Dec 17 '22 18:12

Pie


1 Answers

Polinom operator +(const Polinom &that) {
                   ^^^^^

that is a const reference.

that.vect.push_back(0);//here

Since that is const, so are member access expressions through that reference. Thus that.vect is a const expression.

push_back is a non-const member function. It modifies the vector. The function cannot be called on const vectors.

std::vector<double>::iterator i2 = that.vect.begin();//here

std::vector<T>::begin() const returns a std::vector<T>::const_iterator. It is not implicitly convertible to std::vector<T>::iterator

Solution 1: Don't attempt to push elements into const vectors.

Solution 2: Use a non-const reference when you intend to modify the referred object.

In this case, solution 1. seems to be more sensible. Modifying operands of operator+ would be counter intuitive. Furthermore, you should probably make the function const qualified, and avoid modifying this, for the same reason.

like image 79
eerorika Avatar answered May 23 '23 14:05

eerorika