简体   繁体   中英

How to call postfix operator++?

Suppose I have the following code:

struct ReverseIterator : public Iterator {
ReverseIterator& operator++() {Iterator::operator--();}
ReverseIterator& operator--() {Iterator::operator++();}

ReverseIterator operator++(int) { /* ... */ }
ReverseIterator operator--(int) { /* ... */ }
}

How can I call the base class, Iterator, postfix increment/decrement operators? I understand that to differentiate between pre- and post- fix, a temporary dummy variable is being passed. If that is the case, can't I just call Iteartor::operator++(1); sine 1 is an integer?

You can, but you shoud not to. Postfix inc/dec operator is usually must be implemented through the call of the corresponding prefix form. Moreover, value returned by base class operator is not compatible by type and there will be an error to return it as result of the derived class operator.

struct ReverseIterator : public Iterator {
ReverseIterator& operator++() {Iterator::operator--();}
ReverseIterator& operator--() {Iterator::operator++();}

ReverseIterator operator++(int) 
{
    ReverseIterator result = *this;
    ++(*this);
    return result;
}
ReverseIterator operator--(int) 
{
    ReverseIterator result = *this;
    --(*this);
    return result;
}
}

I suppose you should read these questions: How to implement an STL-style iterator and avoid common pitfalls?

How can I implement various iterator categories in an elegant and efficient way?

Yes, you may use those operators in a normal way, as in ++iterator (prefix) and iterator++ (postfix), but you may call them directly, passing any argument. If you are not actually using the formal parameter anywhere inside the definition, you may pass anything, typically 0 .

Sometimes the argument is used for incrementing by some value, like this:

i.operator++( 25 ); // Increment by 25.

But I wouldn't call that a good programming style. These operators aren't supposed to do this, and it's confusing.

Source.

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