Functions with return values (C++)

前端 未结 6 1106
南旧
南旧 2020-12-11 23:10

When main() calls a function which has a return value of some datatype ( primitive or user-defined ) , the statement in which the function is called is \'usually\' an assign

6条回答
  •  情书的邮戳
    2020-12-11 23:55

    The return value is discarded; as you are not storing it anywhere.

    One important advice:

    Ideally the definition for operator + should look like.

    complex complex::operator + (const complex& c)
    {                            ^^^^^^^^^^^^^^
      complex add; 
      add.real = this->real + c.real;
      add.imag = this->imag + c.imag;
      return add;
    }
    

    In your original code 2 copies of complex are made; among which at least 1 can be avoided with above format where the argument is pass by const reference.

    Also, in your code you should not change the current object; (otherwise it becomes like operator +=()). So create a temporary inside the function and pass it by value.

提交回复
热议问题