当前位置: 代码迷 >> 综合 >> short s1 = 1; s1 = s1 + 1; 和 short s1 = 1; s1 += 1;
  详细解决方案

short s1 = 1; s1 = s1 + 1; 和 short s1 = 1; s1 += 1;

热度:18   发布时间:2023-12-03 14:21:16.0

short s1 = 1; s1 = s1 + 1;编译不能通过

short s1 = 1; s1 += 1;编译可以通过

 

因为:

对于short s1 = 1; s1 = s1 + 1;由于1是int类型,因此s1+1运算结果也是int 型,需要强制转换类型才能赋值给short型。

而short s1 = 1; s1 += 1;可以正确编译,因为s1+= 1;相当于s1 = (short)(s1 + 1);其中有隐含的强制类型转换。

  相关解决方案