开发者

Overloading post increment operator results in argument valued at 0 [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Is it allowed to name the parameter in postfix operator ++?

I created an object to hold a list of objects that maintains the current position internally, so I thought this was a great place to overload the pre and post increment operators, which effectively increment this internal position with bounds checking.

What I noticed is, when you call ++ on the object, the argument is 0.

Test code:

#include <stdio.h>
class A {
public:
   A& operator++(int n) { printf("%d  ", n); return *this; }
};
int main() {
   A a;
   a++;
   a.operator++(0);
   a.operator++(1);
   a.operator++(10);
   return 0;
}

This returns 0 0 1 10. From what I understand, this is normal behavior. So, it has made me rethink how operator++ should work. Previously, I was simply calling ++ on my internal position variable if bounds checking passed. But this has the affect of incrementing by 1 no matter what the input argument is. Next, I though of using the += using the argument n as the right hand side, but as you'll notice, simply calling ++ with no operators (as is customary), gives a zero and the position is not incremented.

Basically, is this开发者_如何学编程 something I should even worry about? If so, how do I detect if the user really wanted 0, or if the default behavior (a++) was intended and I should increment by 1?


You should just ignore the parameter.


The int in the operator is put there or not by the compiler. It indicates whether you have the prefix or sufix operator. (++a a++)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜