C ++ Prefix and Postfix Operators

class compl{ float re,im; public: compl(float r, float i) {re=r; im=i;} compl& operator++() {++re; return*this;} //(1) compl operator++(int k){ compl z=*this; re++; im+=k; return z;} //(2) friend compl& operator--(compl& z) {--z.re; return z;} friend compl operator--(compl& z,int k) {compl x=z; z.re--; z.im-=k; return x;} }; 

(1) Why should we return the current object by reference? As I understand it, a link is just a middle name for something.

(2) Why do we need to save the current object in z, then change the object and return unchanged z? By doing this, we return a value that does not increase. This is due to the way the postfix operator works (it returns the old value and then increments it)

+5
source share
3 answers

(1) You do not have to, but it is idiomatic because it allows chain operators or calls.

(2) Yes, the postfix should return the previous value.

+2
source

1- Operator ++ overload should return by reference, but if you do not need an alias for the variable, you can add a function called the next one or something similar with the same structure.

2- Yes, since you need to return the current value, then increase the variable.

0
source

(1) because we want ++ to return a value, as in

 a = b++; 

and it costs less than returning a copy.

(2) yes, this works postfix operator. This explains why it is usually recommended to write a loop with iterators using prefix increments

 for(iterator it = ..... ; it != .... , ++it) { ...} 

instead of incremental increment: it avoids creating a temporary copy.

-2
source

All Articles