本文介绍了s = s + s和s + = s之间的差异为短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一点测试来操作,我遇到了编译问题。
以下代码编译:

I made a little test to manipulate a short and I came across a compilation problem.The following code compile :

short s = 1;
s += s;

虽然这个没有:

short s = 1;
s = s + s; //Cannot convert from int to short

我读过短裤会自动提升为 int ,但这两个代码有什么区别?

I've read that shorts are automatically promoted to int, but what's the difference between those two codes ?

推荐答案

你是对的被提升为 ints 。这在评估二元运算符 + 期间发生,它被称为二进制数字促销

You're right that short are promoted to ints. This occurs during the evaluation of the binary operator +, and it's known as binary numeric promotion.

但是,使用复合赋值运算符(例如 + = )可以有效地删除它。 状态:

However, this is effectively erased with compound assignment operators such as +=. Section15.26.2 of the JLS states:

也就是说,它等价回到

That is, it's equivalent to casting back to short.

这篇关于s = s + s和s + = s之间的差异为短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 04:34
查看更多