0

Let's look about the next class:

class Complex {
    double re, im;
public:
    Complex(double r = 0 double i = 0);
    Complex& operator-=(const Complex& c);
    Complex operator-() const;
};

How can I decide how to return the result from the function , for example, why in operator-= the value returned by a reference , but, in operator- (unary operator) it's returned by a value?

jww
  • 97,681
  • 90
  • 411
  • 885
Software_t
  • 576
  • 1
  • 4
  • 13
  • `Complex c = (a -= b);` needs operator `-=` to return a ref to `*this` and `Complex d = -a;` requires `operator-` to leave `a` unchanged, but return a temporary (with minus entries) – 463035818_is_not_an_ai Mar 13 '18 at 12:49
  • @user463035818 So while I want to change the value of `*this` it's going to be `by a reference` and otherwise it's going to returned `by a value`? – Software_t Mar 13 '18 at 12:52
  • @user463035818 So it's not a clear. What are the rules about that? In your first comment you just wrote the examples that I wrote in my question, it's not explain when I need to return the result by a reference. – Software_t Mar 13 '18 at 13:03
  • 1
    The examples in my comment **only** work as expected if your operators return whay they do in your code. However, this comments section isnt really the place for good explanations. May I refer you to the duplicate and/or [this](http://en.cppreference.com/w/cpp/language/operators). There are several rules and quirks concerning operator overloading that are imho not really worth remembering. – 463035818_is_not_an_ai Mar 13 '18 at 13:06
  • @user463035818 Ok. Thank you! – Software_t Mar 13 '18 at 13:07

0 Answers0