search

Home  >  Q&A  >  body text

c++ - 谁能帮我看下下面这段代码,多项式乘法和+=操作运行不了,求助啊,到底错在哪了?

伊谢尔伦伊谢尔伦2804 days ago469

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:35:13

    After taking a general look, I have a few questions.

    1. 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.

    2. 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;

    3. When the constructor initializes members, try to use the member initialization list to assign initial values.

    reply
    0
  • Cancelreply