开发者

C++ increment operator

开发者_C百科

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

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

which one?

i++;
++i;


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜