简体   繁体   中英

Overloading postfix ++ operator

Is it some kind of enforced rule that the overload ++ function must take an int as argument to distinguish itself from prefix operators?

Also, In case of prefix overload ++ function, how does the right hand operand is implicit argument?

Eg ++ClassObj //ClassObj is rhs, but usualy lhs is made implicit

On the second issue. Both prefix and postfix ++ are unary operators, they do not have a left-hand-side and right-hand-side operand, but a single operand on which they are applied. That is, in x++ and ++x , x is the operand, not the right hand/left hand, but the operand.

Then on why the int that is required in the signature of the postfix version, it takes an artificial integer argument (which is not used) just to differentiate the signatures and allow the compiler to know that you are declaring/defining a postfix ++ and not the prefix version of it. Consider it as a tag, more than anything else, since the language requires different signatures.

Yes.. It is defined in the standard.

From standard docs 13.5.7 Increment and decrement ,

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.

C++ needs to make a difference in the signature of the function. Unfortunately, both x++ and ++x have only one real argument, namely x . So the C++ designers chose a kind of hack in defining one to require a dummy unused int parameter. That results in different method signatures, and thus a way for the C++ compiler to distinguish the prefix from the postfix operator.

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