从c++到Java,一个显而易见的未回答的问题是为什么Java没有包含操作符重载?

复合物不是a b c吗?A = b + c;比复合物a, b, c简单得多;A = b.add(c);?

是否有一个已知的原因,不允许操作符重载的有效参数?理由是随意的,还是被时间消磨了?


当前回答

Java操作符重载本机支持的替代方案

因为Java没有操作符重载,这里有一些你可以考虑的替代方案:

使用另一种语言。Groovy、Scala和Kotlin都有操作符重载,它们都是基于Java的。 使用Java -oo,这是一个在Java中支持操作符重载的插件。注意,它不是平台独立的。此外,它有许多问题,并且与Java的最新版本(即Java 10)不兼容。(StackOverflow原始源码) 使用JNI、Java本机接口或替代方案。这允许您编写在Java中使用的C或c++方法。当然,这也不是平台独立的。

如果有人知道其他人,请评论,我会把它添加到这个列表中。

其他回答

James Gosling把设计Java比作:

"There's this principle about moving, when you move from one apartment to another apartment. An interesting experiment is to pack up your apartment and put everything in boxes, then move into the next apartment and not unpack anything until you need it. So you're making your first meal, and you're pulling something out of a box. Then after a month or so you've used that to pretty much figure out what things in your life you actually need, and then you take the rest of the stuff -- forget how much you like it or how cool it is -- and you just throw it away. It's amazing how that simplifies your life, and you can use that principle in all kinds of design issues: not do things just because they're cool or just because they're interesting."

你可以在这里阅读引用的上下文

基本上,运算符重载对于对点、货币或复数建模的类非常有用。但在那之后你很快就会用光例子。

另一个因素是开发人员在c++中滥用了这个特性,重载了'&&'、'||'、强制转换操作符,当然还有'new'。将此与传递值和异常相结合所产生的复杂性在《例外c++》一书中有详细介绍。

Java操作符重载本机支持的替代方案

因为Java没有操作符重载,这里有一些你可以考虑的替代方案:

使用另一种语言。Groovy、Scala和Kotlin都有操作符重载,它们都是基于Java的。 使用Java -oo,这是一个在Java中支持操作符重载的插件。注意,它不是平台独立的。此外,它有许多问题,并且与Java的最新版本(即Java 10)不兼容。(StackOverflow原始源码) 使用JNI、Java本机接口或替代方案。这允许您编写在Java中使用的C或c++方法。当然,这也不是平台独立的。

如果有人知道其他人,请评论,我会把它添加到这个列表中。

你可能真的会搬起石头砸自己的脚。这就像指针一样,人们会犯愚蠢的错误,所以我们决定把剪刀拿走。

至少我认为这是原因。 反正我是站在你这边的。:)

Saying that operator overloading leads to logical errors of type that operator does not match the operation logic, it's like saying nothing. The same type of error will occur if function name is inappropriate for operation logic - so what's the solution: drop the ability of function usage!? This is a comical answer - "Inappropriate for operation logic", every parameter name, every class, function or whatever can be logicly inappropriate. I think that this option should be available in respectable programing language, and those that think that it's unsafe - hey no bothy says you have to use it. Lets take the C#. They drooped the pointers but hey - there is 'unsafe code' statement - program as you like on your own risk.

有人说Java中的操作符重载会导致混淆。这些人是否曾经停下来查看一些Java代码进行一些基本的数学运算,比如使用BigDecimal将财务值按百分比增加?.... 这种做法的冗长本身就证明了混淆视听。具有讽刺意味的是,向Java中添加运算符重载将允许我们创建自己的Currency类,这将使此类数学代码优雅而简单(不那么混乱)。