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

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

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


当前回答

从技术上讲,每一种编程语言都有运算符重载,可以处理不同类型的数字,例如整数和实数。解释:术语重载意味着一个函数有多个实现。在大多数编程语言中,为运算符+提供了不同的实现,一个用于整数,一个用于实数,这被称为运算符重载。

Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.

我完全不同意操作符重载会混淆代码的谬论,因为这是由开发人员决定的。这是naïve的想法,老实说,它已经过时了。

+1用于在Java 8中添加操作符重载。

其他回答

假设Java是实现语言,那么a、b和c都是对初始值为null的Complex类型的引用。还假设Complex是不可变的,就像前面提到的BigInteger和类似的不可变BigDecimal一样,我想你是指下面的意思,因为你将引用赋值给从添加b和c返回的Complex,而不是将这个引用与a进行比较。

不是: 复合物a, b, c;A = b + c; 简单得多: 复合物a, b, c;A = b.add(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不允许操作符重载,因为它的创建者没有添加将不同含义与同一个操作符关联起来的功能。他们只是想通过在整个编程语言中保持运算符统一的含义来简化事情。

重载操作符会使事情变得混乱,并为新程序员创造了陡峭的学习曲线。他们只是把运算符重载从教学大纲中去掉了。

从技术上讲,每一种编程语言都有运算符重载,可以处理不同类型的数字,例如整数和实数。解释:术语重载意味着一个函数有多个实现。在大多数编程语言中,为运算符+提供了不同的实现,一个用于整数,一个用于实数,这被称为运算符重载。

Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.

我完全不同意操作符重载会混淆代码的谬论,因为这是由开发人员决定的。这是naïve的想法,老实说,它已经过时了。

+1用于在Java 8中添加操作符重载。