重载后缀 ++操作员
是否存在某种强制规则:overload ++ 函数必须采用 int 作为参数以将其自身与前缀运算符区分开来?
另外,在前缀 overload ++
函数的情况下,右侧操作数如何是隐式参数?
例如 ++ClassObj //ClassObj 是 rhs,但通常 lhs 是隐式的
Is it some kind of enforced rule that the overload ++
function must take an int
as argument to distinguish itself from prefix operators?
Also, In case of prefix overload ++
function, how does the right hand operand is implicit argument?
E.g ++ClassObj //ClassObj is rhs, but usualy lhs is made implicit
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于第二个问题。前缀和后缀
++
都是一元运算符,它们没有左侧和右侧 操作数,但是应用它们的单个操作数。也就是说,在x++
和++x
中,x
是操作数,而不是右手/左手,但是操作数。那么为什么后缀版本的签名中需要
int
,它需要一个人造整数参数(未使用)只是为了区分签名并允许编译器知道您正在声明/定义一个 postfix++
而不是它的 prefix 版本。将其视为一个标签,而不是其他任何东西,因为该语言需要不同的签名。On the second issue. Both prefix and postfix
++
are unary operators, they do not have a left-hand-side and right-hand-side operand, but a single operand on which they are applied. That is, inx++
and++x
,x
is the operand, not the right hand/left hand, but the operand.Then on why the
int
that is required in the signature of the postfix version, it takes an artificial integer argument (which is not used) just to differentiate the signatures and allow the compiler to know that you are declaring/defining a postfix++
and not the prefix version of it. Consider it as a tag, more than anything else, since the language requires different signatures.是的..它是在标准中定义的。
来自标准文档13.5.7增量和减量,
Yes.. It is defined in the standard.
From standard docs 13.5.7 Increment and decrement,
C++ 需要对函数的签名进行修改。不幸的是,
x++
和++x
都只有一个实参,即x
。因此,C++ 设计者选择了一种hack
来定义一个需要一个未使用的虚拟 int 参数的方法。这会产生不同的方法签名,从而为 C++ 编译器提供了一种区分前缀和后缀运算符的方法。C++ needs to make a difference in the signature of the function. Unfortunately, both
x++
and++x
have only one real argument, namelyx
. So the C++ designers chose a kind ofhack
in defining one to require a dummy unused int parameter. That results in different method signatures, and thus a way for the C++ compiler to distinguish the prefix from the postfix operator.