重载后增量运算符会导致参数值为 0
可能的重复:
是否允许在后缀运算符 ++ 中命名参数?
我创建了一个对象来保存在内部维护当前位置的对象列表,因此我认为这是重载前增量运算符和后增量运算符的好地方,这些运算符通过边界检查有效地增量此内部位置。
我注意到,当您在对象上调用 ++
时,参数为 0
。
测试代码:
#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;
}
返回0 0 1 10
。据我了解,这是正常行为。所以,它让我重新思考 operator++
应该如何工作。以前,如果边界检查通过,我只是在内部位置变量上调用 ++
。但无论输入参数是什么,都会增加 1。接下来,我虽然使用 +=
并使用参数 n
作为右侧,但您会注意到,只需调用 ++
> 没有运算符(按照惯例),给出零并且位置不递增。
基本上,这是我应该担心的事情吗?如果是这样,我如何检测用户是否真的想要 0,或者默认行为 (a++
) 是否是有意的并且我应该增加 1?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该忽略该参数。
You should just ignore the parameter.
运算符中的 int 是否放在那里由编译器决定。它指示您是否有前缀或后缀运算符。 (++aa++)
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++)