当我同时使用两个 Java 增量运算符时,我很惊讶。
请检查下面的代码..
public class Testing {
public static void main(String... str) {
int prefix = 0, postfix = 0, both = 0;
// Testing prefix
System.out.println(prefix);
System.out.println(++prefix);
System.out.println(prefix);
// Testing postfix
System.out.println(postfix);
System.out.println(postfix++);
System.out.println(postfix);
// mixing both prefix and postfix (I think this should be fine)
// System.out.println(++ both ++);
}
}
为什么我不能同时使用 ++ 和++
?谁能给我解释一下?谢谢..
最佳答案
++x
或 x++
的结果被归类为值,而不是变量 - 并且两个运算符都将只对变量起作用。
例如,来自section 15.14.2 of the JLS :
A postfix expression followed by a ++ operator is a postfix increment expression.
PostIncrementExpression: PostfixExpression ++
The result of the postfix expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs.
The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.
(15.14.3 中的 PrefixIncrementExpression
使用了几乎相同的语言。)
关于java - 为什么我不能使用多个 Java 递增或递减运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22372621/