prefix and postfix operators c++ -
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 have return current object reference? understood, reference second name something.
(2) why have save current object in z, change object , return unchanged z? doing this, returning value not increased. because of way postfix operator works(it returns old value, , increases it)
(1) don't have to, it's idiomatic because allows chaining operators or calls.
(2) yes, postfix should return previous value.
Comments
Post a Comment