遇到有人在他们的代码中错误地使用 =+
而不是 +=
并且它没有显示为编译错误。
这是因为
int a =+ 2;
与
相同int a = 0 + 2;
?
最佳答案
没有编译错误,因为 +
是一个有效的(尽管相当无用)一元运算符,就像 -
一样:
int x = +1;
int y = -1;
Java 语言规范中的相关部分是Unary Plus Operator + (§15.15.3 ) .它指定调用一元 +
操作会导致 Unary Numeric Promotion (§5.6.1)的操作数。这意味着:
If the operand is of compile-time type
Byte
,Short
,Character
, orInteger
, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of typeint
by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).Otherwise, if the operand is of compile-time type
Long
,Float
, orDouble
, it is subjected to unboxing conversion (§5.1.8).Otherwise, if the operand is of compile-time type
byte
,short
, orchar
, it is promoted to a value of typeint
by a widening primitive conversion (§5.1.2).Otherwise, a unary numeric operand remains as is and is not converted.
In any case, value set conversion (§5.1.13) is then applied.
简而言之,这意味着
- 数字原始包装类型未装箱,并且;
- 小于
int
的整数类型加宽为int
。
关于java - 为什么 =+ 不会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27371075/