为什么= +不会导致编译错误? [英] Why does =+ not cause a compile error?

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

问题描述

在错误的代码中误用了=+而不是+=的人出现,并且没有显示为编译错误.

Came across someone mistakenly using =+ instead of += in their code and it didn't show up as a compile error.

这是因为

int a =+ 2;

int a = 0 + 2;

?

推荐答案

没有编译错误,因为+是有效的(虽然相当无用)一元运算符,其作用方式与-是:

There's no compilation error because + is a valid (albeit fairly useless) unary operator in the same way that - is:

int x = +1;
int y = -1;

Java语言规范中的相关部分是一加运算符+(§15.15.3).它指定调用一元+操作会导致操作数的一元数值提升(§5.6.1).这意味着:

The relevant section in the Java Language Specification is Unary Plus Operator + (§15.15.3 ). It specifies that invoking the unary + operation results in Unary Numeric Promotion (§5.6.1) of the operand. This means that:

  • 如果操作数为编译时类型ByteShortCharacterInteger,则将其进行拆箱转换 (§5.1.8). 然后通过扩展将结果提升为类型int的值 原始转换 (§5.1.2) 或身份转换 (§5.1.1).

  • If the operand is of compile-time type Byte, Short, Character, or Integer, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of type int by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).

否则,如果操作数是编译时类型LongFloatDouble,则将对其进行拆箱转换 (§5.1.8).

Otherwise, if the operand is of compile-time type Long, Float, or Double, it is subjected to unboxing conversion (§5.1.8).

否则,如果操作数是编译时类型byteshortchar,则通过加宽将其提升为类型int的值 原始转换 (§5.1.2).

Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

否则,一元数值操作数将保持不变,并且不会进行转换.

Otherwise, a unary numeric operand remains as is and is not converted.

无论如何,值集转换 (§5.1.13) 然后应用.

In any case, value set conversion (§5.1.13) is then applied.

简而言之,这意味着

  1. 数字原始包装器类型为未装箱,并且;
  2. 小于int
  3. 整数类型被加宽int.
  1. numeric primitive wrapper types are unboxed, and;
  2. integer types smaller than int are widened to int.

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

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