C++ increment operator

2020-08-17 03:06发布

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

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

which one?

i++;
++i;

4条回答
够拽才男人
2楼-- · 2020-08-17 03:52

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楼-- · 2020-08-17 03:56

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.

查看更多
放我归山
4楼-- · 2020-08-17 03:59

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

查看更多
Melony?
5楼-- · 2020-08-17 04:07

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.

查看更多
登录 后发表回答