后缀增量运算符
我有一个自定义类 MyInt,封装了 int m_nValue 数据。后缀运算符
MyInt operator++(int)
{
MyInt temp(*this);
++(*this);
return temp;
}
如果该运算符返回一个对象,那么为什么我无法多次调用 postfix++ 运算符,例如:
MyInt value(10);
value++; // valid
value++++; // Why is this invalid?? Cant it be interpreted as (value++)++
Why does value++++ gets an error lvalue required 如果我可以调用 MyInt 类中定义的 value.print() 方法,那么我也应该能够执行 value++++ 吗?
I have a custom class MyInt, encapsulating a int m_nValue data. The postfix operator
MyInt operator++(int)
{
MyInt temp(*this);
++(*this);
return temp;
}
if the operator returns an object, then why i am not able to call postfix++ operator more than once like:
MyInt value(10);
value++; // valid
value++++; // Why is this invalid?? Cant it be interpreted as (value++)++
Why does value++++ gives an error lvalue required
if i can call value.print() method defined in MyInt Class, then i should also be able to do value++++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误答案:
因为value++
是一个临时变量,保存value
的旧值。你不能++
它。你也不能写15++
!很相似。前者是一个临时变量,后者是一个常量,其中任何一个都不能递增。更正:由于这个答案被接受,我不会更改原始帖子,但是因为人们会阅读它,所以我将在这里发布更正。
首先,我并不是说常量和临时对象是同一个概念。我只是想说临时对象不是左值,就像常量不是一样,但实际上并没有使用左值这个词。
关于
value++++
,它不是一个错误。我刚刚用我的 g++ 4.5 测试了它,它工作得很好。在其他答案中您可以阅读:你所做的事情本质上是错误的:
假设
value
包含10
。第一个value++
将value
更改为11
,但返回一个包含10
的临时对象。然后您++
它将临时值(您从未访问过)更改为11
,但再次返回一个包含10
的临时对象。因此,value++++
的行为与value++
完全相同,只是它做了一些不必要的工作。Wrong answer:
Becausevalue++
is a temporary variable that holds the old value ofvalue
. You can't++
it.You also can't write15++
! It's similar. The former is a temporary variable, the later is a constant, none of which you can increment.Correction: Since this answer got accepted, I am not going to change the original post, but since people will read it, I will post the correction here.
First off, I am not saying constants and temporary objects are the same concept. I was just trying to say temporary objects are not l-values, like constants are not, without actually using the word l-value.
About
value++++
, it is not an error. I just tested it with my g++ 4.5 and it works fine. In other answers you can read:What is inherently wrong about what you are doing is this:
Let's say
value
holds10
. The firstvalue++
changesvalue
to11
but returns a temporary object containing10
. Then you++
it which changes the temporary value (that you never access) to11
, but again returns a temporary object that contains10
. Sovalue++++
behaves exactly likevalue++
except it does some unnecessary work.实际上,这个应该可以工作:
这个运算符基本上只是一个具有奇特语法的普通成员函数,因此你可以在右值上调用它。请注意,正如 Martinho 在他的评论中所解释的那样,效果并不是预期的效果,因为第二个增量是在临时值上运行的。
摘自 2003 年标准第 3.10.10 节:
Actually, this should work:
This operator is basically just a normal member-function with fancy syntax, and as such you can invoke it on an rvalue. Note how, as Martinho explains in his comment, the effect is not the desired one, because the second increment operates on a temporary.
From section 3.10.10 of the 2003 standard: