从c++到Java,一个显而易见的未回答的问题是为什么Java没有包含操作符重载?
复合物不是a b c吗?A = b + c;比复合物a, b, c简单得多;A = b.add(c);?
是否有一个已知的原因,不允许操作符重载的有效参数?理由是随意的,还是被时间消磨了?
从c++到Java,一个显而易见的未回答的问题是为什么Java没有包含操作符重载?
复合物不是a b c吗?A = b + c;比复合物a, b, c简单得多;A = b.add(c);?
是否有一个已知的原因,不允许操作符重载的有效参数?理由是随意的,还是被时间消磨了?
当前回答
有时,操作符重载、友类和多重继承会很好。
然而,我仍然认为这是一个很好的决定。如果Java有运算符重载,那么如果不查看源代码,我们就永远无法确定运算符的含义。目前还没有必要。而且我认为你使用方法而不是操作符重载的例子也是相当可读的。如果你想让事情更清楚,你总是可以在烦人的语句之上添加注释。
// a = b + c
Complex a, b, c; a = b.add(c);
其他回答
有时,操作符重载、友类和多重继承会很好。
然而,我仍然认为这是一个很好的决定。如果Java有运算符重载,那么如果不查看源代码,我们就永远无法确定运算符的含义。目前还没有必要。而且我认为你使用方法而不是操作符重载的例子也是相当可读的。如果你想让事情更清楚,你总是可以在烦人的语句之上添加注释。
// a = b + c
Complex 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操作符重载本机支持的替代方案
因为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.
看看Boost吧。单位:链接文字
它通过操作符重载提供零开销的维数分析。这一点还能清楚多少呢?
quantity<force> F = 2.0*newton;
quantity<length> dx = 2.0*meter;
quantity<energy> E = F * dx;
std::cout << "Energy = " << E << endl;
实际上会输出“Energy = 4 J”,这是正确的。