为什么Java的+ =, - =,* =,/ =复合赋值运算符需要转换? [英] Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
问题描述
直到今天,我认为例如:
Until today, I thought that for example:
i += j;
只是一个快捷方式:
i = i + j;
但如果我们试试这个:
int i = 5;
long j = 8;
然后 i = i + j;
将不编译,但 i + = j;
编译正常。
Then i = i + j;
will not compile but i += j;
will compile fine.
这是否意味着实际上 i + = j;
是这样的快捷方式
i =(i的类型)(i + j)
?
Does it mean that in fact i += j;
is a shortcut for something like this
i = (type of i) (i + j)
?
推荐答案
与这些问题一样,JLS也有答案。在这种情况下§15.26.2复合赋值运算符一>。提取:
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
表格
E1的复合作业表达式 op = E2
相当于E1 = (T)((E1) op (E2))
,其中T
是E1
的类型,但E1
仅评估一次。
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
引自§15.26.2
[...]以下代码是正确的:
[...] the following code is correct:
short x = 3;
x += 4.6;
并导致x的值为7,因为它相当于:
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
换句话说,您的假设是正确的。
In other words, your assumption is correct.
这篇关于为什么Java的+ =, - =,* =,/ =复合赋值运算符需要转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!