++i 与 i++ 的实现是否相同?因语言而异?
我最近读到: “表达式 (++i) 和 (i++) 具有值和副作用。 副作用是 i 中的值增加 1。 (i++) 的值是增量之前的值, (++i)的值是增量后的值, 但无论是先递增还是先求值, 不是 C 的一部分。”
我知道评估步骤首先在 Java 中进行……对于所有其他语言都一样吗?
I recently read:
"The expressions (++i) and (i++) have values and side effects.
The side effect is that the value in i is increased by 1.
The value of (i++) is the value before the increment and
the value of (++i) is the value after the increment,
but whether the increment or the evaluation takes place first,
is not part of C."
I know the evaluative step takes place first in Java... is it the same for all other languages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至少在 C++ 中,运算符可以重载,因此不能保证
++i
和i++
的语义 - 事实上它们可以重载以执行非常不同的操作,并且甚至可以做一些与增量无关的事情。所以你的问题的答案是不 - 在至少一种语言中,类的后缀和前缀++
运算符可以执行程序员希望的任何操作。但仅仅因为有人可以做到这一点,并不意味着他们应该这样做。由于预自增和后自增运算符具有众所周知的语义,(体面的)C++ 程序员尽量不违反这一点,以免使用它们的代码感到最惊讶。
C++ 中运算符重载的一个很好的例子是 STL 迭代器。像链表这样的容器的迭代器定义了一个类,它以模仿指针的方式重载前增量和后增量运算符(C++ 中的迭代器实际上是指针的泛化)。
At least in C++, operators can be overloaded, so the semantics of
++i
andi++
are not guaranteed - they can in fact be overloaded to do very different things, and can even be made to do something that has nothing to do with increment. So the answer to your question is that no - in at least one language, the postfix and prefix++
operator for classes can do whatever the programmer wishes.But just because someone can do that, it doesn't mean they should. Since the pre- and post-increment operators have very well known semantics, (decent) C++ programmers try to not violate that, lest the code that uses them will be most surprised.
A good example of operator overloading in C++ is the STL iterators. Iterators to containers like linked lists define a class that overloads the preincrement and postincrement operators in such a way that it mimics a pointer (iterators in C++ are in fact a generalization of pointers).