问题描述
int anInt = 1;
double aDouble = 2.5;
anInt = anInt + aDouble; // Error - need to cast double to int
anInt += aDouble; // This is ok. Why?
anInt = aDouble; // This is also an error.
anInt = 1 + aDouble; // This is also an error.
所以我的问题是:为什么 anInt不是编译错误+ = aDouble
?
So my questions is: Why is it not a compile error to do anInt += aDouble
?
推荐答案
四个案例中有三个正确报告错误。复合赋值是规则的唯一例外。 Java语言规范,第15.26.2节,解释了原因:
Three of the four cases properly report an error. Compound assignment is the only exception from the rule. Java Language Specification, part 15.26.2, explains why:
表格 E1 op = E2
的复合赋值表达式相当于 E1
,其中
=(T)((E1)op(E2)) T
是 E1 $的类型c $ c>,但
E1
仅评估一次。
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.
例如,以下代码是正确的:
For example, 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);
如您所见,隐式插入可以避免错误演员。
As you can see, the error is avoided by implicit insertion of a cast.
这篇关于Java Puzzler - 将double转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!