Why use int as an argument for post-increment operator overload?

半世苍凉 提交于 2020-01-21 12:09:50

问题


As I know here is the way to overload the post-increment operator:

const MyClass& MyClass::operator++(int);

Why does it have int as an argument?


回答1:


D&E, §11.5.3:

I conisdered the obvious solution, adding the keywords prefix and postfix to C++ [ ... ] However I received the usual howl of outrage from people who dislike new keywords. Several alternatives that did not involve new keywords were suggested. For example:

class Ptr_to_X {
    X ++operator(); // prefix ++
    X operator++(); // postfix ++
};

or

class Ptr_to_X {
    X& operator++(); // postfix because it 
                     // returns a reference
    x operator();    // prefix because it
                     // doesn't return a reference
};

I considered the former too cute and the latter too subtle. Finally I settled on:

class Ptr_to_X {
    X operator++();     // prefix: no argument
    X operator++(int);  // postfix: because of the argument
};

This may be too cute and too subtle, but it works, requires no new syntax, and has a logic to the madness. Other unary operators are prefix and take no arguments when defined as member functions. The "odd" and unused dummy int argument is used to indicate the odd postfix operators. In other words, in the postfix case, ++ comes between the first (real) operand and the second (dummy) argument and is thus postfix.

These explanations are needed because the mechanism is unique, and therefore a bit of a wart. Given a choice I would probably have introduced the prefix and postfix keywords, but that didn't appear feasible at the time.




回答2:


This is to distinguish between prefix increment and postfix increment operators.

For completeness, this is set out in §13.5.7 in both the C++03 and the C++11 standards.



来源:https://stackoverflow.com/questions/12740378/why-use-int-as-an-argument-for-post-increment-operator-overload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!