-->

C++ increment operator

2020-08-17 03:48发布

问题:

How to differentiate between overloading the 2 versions of operator ++ ?

const T& operator ++(const T& rhs)

which one?

i++;
++i;

回答1:

These operators are unary, i.e., they do not take a right hand side parameter.

As for your question, if you really must overload these operators, for the preincrement use the signature const T& operator ++(), and for the postincrement, const T& operator(int). The int parameter is a dummy.



回答2:

For the non-member versions, a function with one parameter is prefix while a function with two parameters and the second being int is postfix:

struct X {};
X& operator++(X&);      // prefix
X  operator++(X&, int); // postfix

For the member-versions, the zero-parameter version is prefix and the one-parameter version taking int is postfix:

struct X {
    X& operator++();    // prefix
    X  operator++(int); // postfix
};

The int parameter to calls of the postfix operators will have value zero.



回答3:

for the postfix ++ and -- operators, the function must take a dummy int argument. if it has no argument, then it's the prefix operator



回答4:

Think of postfix increment i++ as having a second (missing) parameter (i.e. i++x). So postfix increment signature has a righthand parameter while the prefix increment does not.