#defining operators in class

8 messages · Page 1 of 1 (latest)

tranquil hemlock
#

imagine we have a class "complex"
question: why do we use "&" in definition of two part operations but not in definition of one part operations, or am i wrong or somen (like we can do both?)?

e.g. :

class complex {
  double real, imaginary;
public:
  complex& operator+=(complex x) { a calculation }
  complex operator+(complex x, complex y) { another calculation }
}
radiant echo
#

so you can something like this

int a = 3;
(a += 4) += 5;
#

in other words, you can chain them

#

nothing requires you to return a reference, you could return void but that would make it impossible to objects of your class like this

tranquil hemlock
#

🤔

#

sorry i didnt understand i should ponder more lol

radiant echo
#

since the expression (a += 4) returns a reference to a, you can use another operator on it

#

likewise

struct something {
  something& operator+=(something s);
  void operator-=(something s);
}

int main(){
  something s1, s2, s3;
  (s1 += s2) += s3; // ok, since += returns a reference
  (s1 -= s2) -= s3; // error, can't use -= with operands of type 'void' and something
}