问题描述
如果我有一个字节变量: byte b = 0;
If I have a byte variable: byte b = 0;
为什么以下工作:
b++;
b += 1; // compiles
...但这不是吗?
b = b + 1; // compile error
编译器首先理解 byte
和第二个 int
?
Does compiler understand first as byte
and second as int
?
我知道施法,但我想提请你注意 b ++,b + = 1和b = b + 1
I know casting but I want to draw your attention to the b++, b += 1 and b = b + 1
我认为它们是平等的,为什么编译器会区别呢?有什么区别
I think they are equal so why compiler differs them ? what is the difference between
b += 1 and b = b + 1 ?
推荐答案
因为 b + = 1
相当于 b =(byte)(b + 1)
,而类型 b + 1
升级为 int
()因此无法在没有显式转换的情况下将其结果分配给 byte
。
Because b += 1
is an equivalent to b = (byte)(b + 1)
, whereas type of b + 1
is promoted to int
(JLS §5.6.2 Binary Numeric Promotion) and therefore its result cannot be assigned to byte
without explicit conversion.
来自:
这篇关于为什么byte + = 1编译但是byte = byte + 1不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!