标题说的是什么。对于 C++,(++a)++
会编译。不过,奇怪的是,++(a++)
不会:
int main() {
int a = 0;
++a++; // does not compile
(++a)++; // does compile
++(a++); // does not compile
}
但在 Java 中,它并不适用于所有这三个:
public class Test {
public static void main(String[] args) {
int a = 0;
++a++; // does not compile
(++a)++; // does not compile
++(a++); // does not compile
}
}
C++ 编译它而不是 Java 有什么原因吗?
所有示例都无法在 Java 中运行,因为后缀和前缀递增操作都返回值 而不是变量 我们可以通过转到 JLS 看到这一点关于 Postfix Increment Operator ++ 的部分举个例子,它说:
The result of the postfix increment expression is not a variable, but a value.
Prefix Increment Operator ++ 的 JLS 部分说同样的话。
这就像尝试增加文字值 ( see it live ):
2++ ;
++3 ;
出现以下错误:
required: variable
found: value
这与我们在您的示例中收到的错误相同。
在 C++ 中,前缀增量返回一个左值,但后缀增量返回一个纯右值,并且 C++ 中的前缀和后缀增量都需要一个左值。所以你的第一个和第三个 C++ 示例:
++a++;
++(a++)
失败是因为您正试图将前缀增量应用于纯右值。而第二个 C++ 示例:
(++a)++;
没问题,因为前缀增量返回一个左值。
供引用draft C++ standard在 5.2
后缀表达式 中说:
The value of a postfix ++ expression is the value of its operand [...] The operand shall be a modifiable lvalue
和:
The result is a prvalue
5.3
一元表达式 说:
The operand of prefix ++ is modified [...] The
operand shall be a modifiable lvalue
和:
The result is the updated operand; it is an lvalue