PHP中文网2017-04-17 13:35:13
After taking a general look, I have a few questions.
There are problems with the definition of several compound assignment operators, such as:
Polynomial& operator+=(const Polynomial&x) {
return *this+ x; // 此处返回了局部变量的引用,是未定义行为
}
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.