简体   繁体   中英

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 do we have to return current object by reference? As I understood, reference is just a second name for something.

(2) Why do we have to save current object in z, then change the object and return the unchanged z? Doing this, we are returning the value that is not increased. Is it because of the way that postfix operator works(it returns the old value, and then increases it)

(1) You don't have to, but it's idiomatic because it allows for chaining operators or calls.

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

1- Operator ++ overloading must return by reference but if you don't need an alias for the variable you can add a function called next or anything like that with the same structure.

2- Yes, as you need to return current value then increment the variable.

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

a = b++;

and it costs less than returning a copy.

(2) yes, it is the way the postfix operator work. This explains why it is generally recommended to write a loop with iterators using prefix incrementation

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

instead of postfix incrementation: it avoids building a temporary copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM