简写赋值运算符,+=,真正的含义? [英] Short hand assignment operator, +=, True Meaning?

查看:32
本文介绍了简写赋值运算符,+=,真正的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到i+=2i=i+2 的简写.但现在我对此表示怀疑.对于下面的代码,上面的知识没有用:

I learnt that i+=2 is the short-hand of i=i+2. But now am doubting it. For the following code, the above knowledge holds no good:

byte b=0;b=b+2;//错误:必需字节,找到整数

byte b=0; b=b+2; //Error:Required byte, Found int

上面的代码是有道理的,因为2int类型,表达式返回int值.

The above code is justifiable, as 2 is int type and the expression returns int value.

但是,以下代码运行良好:

But, the following code runs fine:

byte b=0;b+=2;//b 在 += 操作后存储 2

这迫使我怀疑 += 简写运算符比我所知道的更多.请赐教.

This is forcing me to doubt that the += short-hand operator is somewhat more than I know. Please enlighten me.

推荐答案

如有疑问,您可以随时查看 Java 语言规范.在这种情况下,相关部分是 15.26.2,复合赋值运算符.

When in doubt, you can always check the Java Language Specification. In this case, the relevant section is 15.26.2, Compound Assignment Operators.

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.

所以你几乎是正确的,除了还添加了演员表.在你的情况下:b+=2; 符合 b=(byte)(b+2);

So you were almost correct, except that a cast is added as well. In your case: b+=2; qualifies to b=(byte)(b+2);

这篇关于简写赋值运算符,+=,真正的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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