从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设计人员认为操作符重载带来的麻烦大于它的价值。就这么简单。
在一种每个对象变量实际上都是引用的语言中,运算符重载具有相当不合逻辑的额外危险——至少对c++程序员是这样。比较c#的==操作符重载和Object的情况。等号和对象。ReferenceEquals(或其他名称)。
其他回答
看看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”,这是正确的。
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++》一书中有详细介绍。
这不是一个很好的理由来禁止它,而是一个实际的理由:
人们并不总是负责任地使用它。请看下面这个来自Python库scapy的例子:
>>> IP()
<IP |>
>>> IP()/TCP()
<IP frag=0 proto=TCP |<TCP |>>
>>> Ether()/IP()/TCP()
<Ether type=0x800 |<IP frag=0 proto=TCP |<TCP |>>>
>>> IP()/TCP()/"GET / HTTP/1.0\r\n\r\n"
<IP frag=0 proto=TCP |<TCP |<Raw load='GET / HTTP/1.0\r\n\r\n' |>>>
>>> Ether()/IP()/IP()/UDP()
<Ether type=0x800 |<IP frag=0 proto=IP |<IP frag=0 proto=UDP |<UDP |>>>>
>>> IP(proto=55)/TCP()
<IP frag=0 proto=55 |<TCP |>>
下面是解释:
/操作符用作两个操作符之间的复合操作符 层。当这样做时,下层可以有一个或多个它的 默认字段根据上层重载。(你仍然 可以给出你想要的值)。字符串可以用作原始层。
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(参数)'方法。