为什么byte + = 1编译但是byte = byte + 1不是? [英] why byte += 1 compile but byte = byte + 1 not?

查看:283
本文介绍了为什么byte + = 1编译但是byte = byte + 1不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字节变量: 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 JLS§5.6.2二进制数字促销)因此无法在没有显式转换的情况下将其结果分配给 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.

来自 JLS,§15.26.2Compound赋值运算符


E1 op = E2形式的复合赋值表达式等效于E1 =(T)(( E1)op(E2)),其中T是E1的类型,除了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.

这篇关于为什么byte + = 1编译但是byte = byte + 1不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆