The reason is that *this+x calls Polynomial::operator+ and returns a new Polynomial variable. This variable is a local variable of operator+=, and the return value of operator+= is a reference to this new variable, so it is Undefined behavior. Several other compound assignment operators are similar.
The implementation of several operator overloading is not very good, such as:
Only one of operator!= and operator== needs to be implemented specifically, and the other should call the implemented one;
operator+= should be implemented specifically, and operator+ should call operator+=. Please refer to the reason here. Subtraction and multiplication are similar;
When the constructor initializes members, try to use the member initialization list to assign initial values.
After taking a general look, I have a few questions.
There are problems with the definition of several compound assignment operators, such as:
The reason is that
*this+x
callsPolynomial::operator+
and returns a newPolynomial
variable. This variable is a local variable ofoperator+=
, and the return value ofoperator+=
is a reference to this new variable, so it is Undefined behavior. Several other compound assignment operators are similar.The implementation of several operator overloading is not very good, such as:
Only one of
operator!=
andoperator==
needs to be implemented specifically, and the other should call the implemented one;operator+=
should be implemented specifically, andoperator+
should calloperator+=
. Please refer to the reason here. Subtraction and multiplication are similar;When the constructor initializes members, try to use the member initialization list to assign initial values.