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

复合物不是a b c吗?A = b + c;比复合物a, b, c简单得多;A = b.add(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.

其他回答

Groovy具有操作符重载,并且运行在JVM中。如果您不介意性能损失(每天都在减小)。它是基于方法名自动生成的。例如,'+'调用'plus(参数)'方法。

假设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);

Java设计人员认为操作符重载带来的麻烦大于它的价值。就这么简单。

在一种每个对象变量实际上都是引用的语言中,运算符重载具有相当不合逻辑的额外危险——至少对c++程序员是这样。比较c#的==操作符重载和Object的情况。等号和对象。ReferenceEquals(或其他名称)。

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

看看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”,这是正确的。