c++ - Polynomial++: How to increment p(x) by 1 -
i have polynomial
class, , trying define operator++
, both pre- , post- incrementation, trying define pre- , post- decrementation, namely operator--
. here snippet of code:
class polynomial { public: polynomial(); polynomial(vector<int>coeffs); /* . . . */ polynomial operator++(); polynomial& operator++ (int unused); polynomial operator--(); polynomial& operator-- (int unused); /* . . . */ private: vector<int> coefficient; }; polynomial polynomial::operator++() { coefficient[0]++; return *this; } polynomial& polynomial::operator++ (int unused) { polynomial copy(*this); coefficient[0]++; return copy; } polynomial polynomial::operator--() { coefficient[0]--; return *this; } polynomial& polynomial::operator-- (int unused) { polynomial copy(*this); coefficient[0]--; return copy; }
i error when trying in main:
polynomial p(
...some vector...);
cout << p++;
you returning references temporaries postfix operators:
polynomial& polynomial::operator++ (int unused) { polynomial copy(*this); coefficient[0]++; return copy; // returning reference local variable }
this undefined behaviour. have return type of post , pre-increment wrong way around. need this:
polynomial& operator++(); polynomial operator++ (int); polynomial& operator--(); polynomial operator-- (int);
Comments
Post a Comment