Java的一元加运算符的目的是什么? [英] What is the purpose of Java's unary plus operator?

查看:433
本文介绍了Java的一元加运算符的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 an int 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.

这个SO问题,关于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中,不能重载任何运算符。那么这个一元加运算符只存在于Java中,因为它存在于C ++中吗?

However, in Java, one cannot overload any operator. So does this unary plus operator exist in Java only because it existed in C++?

推荐答案

一元加运算符执行自动转换为 int 当其操作数的类型为 byte 时, char ,或。这称为一元数字促销,它使您能够执行以下操作:

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屋!

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