gpt4 book ai didi

java - 为什么Java的+ =,-=,* =,/=复合赋值运算符不需要强制转换?

转载 作者:行者123 更新时间:2023-12-02 10:43:00 25 4
gpt4 key购买 nike

直到今天,我还以为例如:

i += j;

只是以下方面的捷径:
i = i + j;

但是,如果我们尝试这样做:
int i = 5;
long j = 8;

然后 i = i + j;将不会编译,但是 i += j;将可以正常编译。

这是否意味着 i += j;实际上是诸如此类的快捷方式 i = (type of i) (i + j)

最佳答案

与这些问题一样,JLS保留答案。在这种情况下§15.26.2 Compound Assignment Operators。摘录:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.



§15.26.2引用的一个例子

[...] the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);


换句话说,您的假设是正确的。

关于java - 为什么Java的+ =,-=,* =,/=复合赋值运算符不需要强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com