Java的一元加运算符的目的是什么? [英] What is the purpose of Java's unary plus operator?
问题描述
Java 的一元加号运算符似乎是通过 C++ 从 C 过来的.
Java's unary plus operator appears to have come over from C, via C++.
int result = +1;
它似乎有以下效果:
- 拆箱它的操作数,如果它是一个包装对象
- 将其操作数提升为
int
,如果它不是int
或更宽的 - 使包含大量连续加号的邪恶表达式的解析稍微复杂化
- Unboxes its operand, if it's a wrapper object
- Promotes its operand to
int
, if it's not already anint
or wider - Complicates slightly the parsing of evil expressions containing large numbers of consecutive plus signs
在我看来,有更好/更清晰的方法来完成所有这些事情.
It seems to me that there are better/clearer ways to do all of these things.
在 this SO question中,关于 C# 中的对应运算符,有人说如果你觉得需要,它就会超载."
In this SO question, concerning the counterpart operator in C#, someone said that "It's there to be overloaded if you feel the need."
然而,在Java中,不能重载任何运算符.那么这个一元加号运算符是否仅仅因为存在于 C++ 中就存在于 Java 中?
However, in Java, one cannot overload any operator. So does this unary plus operator exist in Java only because it existed in C++?
推荐答案
当其操作数的类型为 byte
时,一元加运算符执行自动转换为 int
,char
或 short
.这称为一元数字提升,它使您能够执行以下操作:
The unary plus operator performs an automatic conversion to int
when the type of its operand is byte
, char
, or short
. This is called unary numeric promotion, and it enables you to do things like the following:
char c = 'c';
int i = +c;
当然,它的用途有限.但它确实是有目的的.请参阅规范,特别是部分 §15.15.3 和 §5.6.1.
Granted, it's of limited use. But it does have a purpose. See the specification, specifically sections §15.15.3 and §5.6.1.
这篇关于Java的一元加运算符的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!