为什么 Java 不提供运算符重载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/77718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't Java offer operator overloading?
提问by
Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?
从 C++ 到 Java,明显没有答案的问题是为什么 Java 不包括运算符重载?
Isn't Complex a, b, c; a = b + c;
much simpler than Complex a, b, c; a = b.add(c);
?
不是Complex a, b, c; a = b + c;
比 简单得多Complex a, b, c; a = b.add(c);
吗?
Is there a known reason for this, valid arguments for notallowing operator overloading? Is the reason arbitrary, or lost to time?
是否存在已知的原因,有效的论据,不使运算符重载?原因是武断的,还是时间错了?
采纳答案by Aaron
Assuming you wanted to overwrite the previous value of the object referred to by a
, then a member function would have to be invoked.
假设您想覆盖由 引用的对象的先前值a
,则必须调用成员函数。
Complex a, b, c;
// ...
a = b.add(c);
In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and copythe resultant value from the temporary object into the existing object a
.
在 C++ 中,此表达式告诉编译器在堆栈上创建三 (3) 个对象,执行加法,并将结果值从临时对象复制到现有对象中a
。
However, in Java, operator=
doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named Complex
, assignment means to copy a reference to an existing value.
但是,在 Java 中,operator=
不会对引用类型进行值复制,用户只能创建新的引用类型,而不能创建值类型。因此,对于名为 的用户定义类型Complex
,赋值意味着复制对现有值的引用。
Consider instead:
考虑一下:
b.set(1, 0); // initialize to real number '1'
a = b;
b.set(2, 0);
assert( !a.equals(b) ); // this assertion will fail
In C++, this copies the value, so the comparison will result not-equal. In Java, operator=
performs reference copy, so a
and b
are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself.
在 C++ 中,这会复制值,因此比较将导致不相等。在 Java 中,operator=
执行引用复制,因此a
和b
现在引用相同的值。结果,比较将产生“相等”,因为对象将与自身相等。
The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- operator+
would likely deal with values and objects, but operator=
is already implemented to deal with references.
副本和引用之间的差异只会增加运算符重载的混乱。正如@Sebastian 所提到的,Java 和 C# 都必须分别处理值和引用相等性——operator+
可能会处理值和对象,但operator=
已经实现来处理引用。
In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on Complex
, operator=
and operator==
are both working on values -- copying values and comparing values respectively.
在 C++ 中,您应该一次只处理一种比较,这样就不会那么混乱。例如,在Complex
,operator=
并且operator==
都致力于价值-复制值分别比较值。
回答by Sarien
Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.
好吧,您真的可以在操作员超载的情况下用脚射击自己。就像人们用指针犯了愚蠢的错误一样,所以决定把剪刀拿走。
At least I think that's the reason. I'm on your side anyway. :)
至少我认为这就是原因。反正我是站在你这边的。:)
回答by user14128
I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.
我认为这可能是一种有意识的设计选择,它迫使开发人员创建名称清楚地传达其意图的函数。在 C++ 中,开发人员会用通常与给定运算符的普遍接受的性质无关的功能来重载运算符,这使得几乎不可能在不查看运算符的定义的情况下确定一段代码的作用。
回答by Sebastian Redl
The Java designers decided that operator overloading was more trouble than it was worth. Simple as that.
Java 设计者认为运算符重载带来的麻烦比其价值还多。就那么简单。
In a language where every object variable is actually a reference, operator overloading gets the additional hazard of being quite illogical - to a C++ programmer at least. Compare the situation with C#'s == operator overloading and Object.Equals
and Object.ReferenceEquals
(or whatever it's called).
在每个对象变量实际上都是一个引用的语言中,运算符重载会带来非常不合逻辑的额外风险——至少对 C++ 程序员来说是这样。将这种情况与 C# 的 == 运算符重载和Object.Equals
和Object.ReferenceEquals
(或任何名称)进行比较。
回答by David Schlosnagle
Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned BigIntegerand similar immutable BigDecimal, I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.
假设 Java 作为实现语言,那么 a、b 和 c 都将是对 Complex 类型的引用,初始值为 null。还假设 Complex 是不可变的,因为提到的BigInteger和类似的不可变BigDecimal,我认为您的意思如下,因为您将引用分配给从添加 b 和 c 返回的 Complex,而不是将此引用与 a 进行比较。
Isn't :
Complex a, b, c; a = b + c;
muchsimpler than:
Complex a, b, c; a = b.add(c);
是不是:
Complex a, b, c; a = b + c;
比以下简单得多:
Complex a, b, c; a = b.add(c);
回答by noah
回答by Garth Gilmour
James Gosling likened designing Java to the following:
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."
“当你从一间公寓搬到另一间公寓时,有一个关于搬家的原则。一个有趣的实验是把你的公寓收拾好,把所有的东西都放在盒子里,然后搬到下一个公寓,在你需要它之前不要打开任何东西。所以你'重新做你的第一顿饭,然后你从盒子里拿出一些东西。然后大约一个月后,你已经用它来弄清楚你生活中真正需要什么东西,然后你把剩下的东西拿走东西——忘记你有多喜欢它或者它有多酷——然后你就把它扔掉。令人惊奇的是,它简化了你的生活,你可以在各种设计问题中使用这个原则:不要仅仅因为它们而做事情很酷,或者只是因为它们很有趣。”
You can read the context of the quote here
Basically operator overloading is great for a class that models some kind of point, currency or complex number. But after that you start running out of examples fast.
基本上,运算符重载非常适合模拟某种点、货币或复数的类。但是在那之后,您开始快速用完示例。
Another factor was the abuse of the feature in C++ by developers overloading operators like '&&', '||', the cast operators and of course 'new'. The complexity resulting from combining this with pass by value and exceptions is well covered in the Exceptional C++book.
另一个因素是开发人员在 C++ 中滥用了 C++ 中的功能,他们重载了像“&&”、“||”这样的运算符、强制转换运算符,当然还有“new”。将其与值传递和异常相结合所产生的复杂性在Exceptional C++书中有很好的介绍。
回答by Garth Gilmour
Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.
有时,拥有运算符重载、友元类和多重继承会很好。
However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.
不过我仍然认为这是一个很好的决定。如果 Java 有运算符重载,那么我们永远无法在不查看源代码的情况下确定运算符的含义。目前没有这个必要。而且我认为您使用方法而不是运算符重载的示例也很有可读性。如果您想让事情更清楚,您可以随时在毛茸茸的陈述上方添加评论。
// a = b + c
Complex a, b, c; a = b.add(c);
回答by user15793
Check out Boost.Units: link text
查看 Boost.Units:链接文本
It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?
它通过运算符重载提供零开销的维度分析。这能清楚多少?
quantity<force> F = 2.0*newton;
quantity<length> dx = 2.0*meter;
quantity<energy> E = F * dx;
std::cout << "Energy = " << E << endl;
would actually output "Energy = 4 J" which is correct.
实际上会输出“Energy = 4 J”,这是正确的。
回答by paercebal
There are a lot of posts complaining about operator overloading.
有很多帖子抱怨运算符重载。
I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.
我觉得我必须澄清“运算符重载”的概念,为这个概念提供另一种观点。
Code obfuscating?
代码混淆?
This argument is a fallacy.
这种说法是谬论。
Obfuscating is possible in all languages...
所有语言都可以进行混淆......
It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:
通过函数/方法混淆 C 或 Java 中的代码就像在 C++ 中通过运算符重载混淆代码一样容易:
// C++
T operator + (const T & a, const T & b) // add ?
{
T c ;
c.value = a.value - b.value ; // subtract !!!
return c ;
}
// Java
static T add (T a, T b) // add ?
{
T c = new T() ;
c.value = a.value - b.value ; // subtract !!!
return c ;
}
/* C */
T add (T a, T b) /* add ? */
{
T c ;
c.value = a.value - b.value ; /* subtract !!! */
return c ;
}
...Even in Java's standard interfaces
...即使在 Java 的标准接口中
For another example, let's see the Cloneable
interfacein Java:
再举一个例子,让我们看看Java中的Cloneable
接口:
You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:
您应该克隆实现此接口的对象。但你可以撒谎。并创建一个不同的对象。事实上,这个接口太弱了,你可以完全返回另一种类型的对象,只是为了好玩:
class MySincereHandShake implements Cloneable
{
public Object clone()
{
return new MyVengefulKickInYourHead() ;
}
}
As the Cloneable
interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?
由于Cloneable
接口可以被滥用/混淆,它是否应该以 C++ 运算符重载的相同理由被禁止?
We could overload the toString()
method of a MyComplexNumber
class to have it return the stringified hour of the day. Should the toString()
overloading be banned, too? We could sabotage MyComplexNumber.equals
to have it return a random value, modify the operands... etc. etc. etc..
我们可以重载toString()
一个MyComplexNumber
类的方法,让它返回一天中的字符串化小时。toString()
超载也应该被禁止吗?我们可以破坏MyComplexNumber.equals
它返回一个随机值,修改操作数......等等等等。
In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a add
function that adds, and Cloneable
implementation method that clones, and a ++
operator than increments.
在 Java 中,就像在 C++ 或任何语言中一样,程序员在编写代码时必须遵守最低限度的语义。这意味着实现一个add
添加的函数Cloneable
,和一个克隆的实现方法,以及一个++
比递增的运算符。
What's obfuscating anyway?
到底有什么好混淆的?
Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?
既然我们知道即使通过原始的 Java 方法也可以破坏代码,我们可以问问自己,C++ 中运算符重载的真正用途是什么?
Clear and natural notation: methods vs. operator overloading?
清晰自然的符号:方法与运算符重载?
We'll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.
下面我们将在不同情况下比较Java和C++中“相同”的代码,以了解哪种编码风格更清晰。
Natural comparisons:
自然比较:
// C++ comparison for built-ins and user-defined types
bool isEqual = A == B ;
bool isNotEqual = A != B ;
bool isLesser = A < B ;
bool isLesserOrEqual = A <= B ;
// Java comparison for user-defined types
boolean isEqual = A.equals(B) ;
boolean isNotEqual = ! A.equals(B) ;
boolean isLesser = A.comparesTo(B) < 0 ;
boolean isLesserOrEqual = A.comparesTo(B) <= 0 ;
Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...
请注意,只要提供运算符重载,A 和 B 可以是 C++ 中的任何类型。在 Java 中,当 A 和 B 不是基元时,代码会变得非常混乱,即使对于类基元的对象(BigInteger 等)...
Natural array/container accessors and subscripting:
自然数组/容器访问器和下标:
// C++ container accessors, more natural
value = myArray[25] ; // subscript operator
value = myVector[25] ; // subscript operator
value = myString[25] ; // subscript operator
value = myMap["25"] ; // subscript operator
myArray[25] = value ; // subscript operator
myVector[25] = value ; // subscript operator
myString[25] = value ; // subscript operator
myMap["25"] = value ; // subscript operator
// Java container accessors, each one has its special notation
value = myArray[25] ; // subscript operator
value = myVector.get(25) ; // method get
value = myString.charAt(25) ; // method charAt
value = myMap.get("25") ; // method get
myArray[25] = value ; // subscript operator
myVector.set(25, value) ; // method set
myMap.put("25", value) ; // method put
In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.
在 Java 中,我们看到对于每个容器做同样的事情(通过索引或标识符访问其内容),我们有不同的方式来做,这很令人困惑。
In C++, each container uses the same way to access its content, thanks to operator overloading.
在 C++ 中,由于运算符重载,每个容器都使用相同的方式访问其内容。
Natural advanced types manipulation
自然高级类型操作
The examples below use a Matrix
object, found using the first links found on Google for "Java Matrix object" and "C++ Matrix object":
下面的示例使用一个Matrix
对象,该对象是使用在 Google 上找到的第一个链接找到的“ Java 矩阵对象”和“ C++ 矩阵对象”:
// C++ YMatrix matrix implementation on CodeProject
// http://www.codeproject.com/KB/architecture/ymatrix.aspx
// A, B, C, D, E, F are Matrix objects;
E = A * (B / 2) ;
E += (A - B) * (C + D) ;
F = E ; // deep copy of the matrix
// Java JAMA matrix implementation (seriously...)
// http://math.nist.gov/javanumerics/jama/doc/
// A, B, C, D, E, F are Matrix objects;
E = A.times(B.times(0.5)) ;
E.plusEquals(A.minus(B).times(C.plus(D))) ;
F = E.copy() ; // deep copy of the matrix
And this is not limited to matrices. The BigInteger
and BigDecimal
classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.
这不仅限于矩阵。Java的BigInteger
和BigDecimal
类遭受同样令人困惑的冗长,而它们在 C++ 中的等价物与内置类型一样清晰。
Natural iterators:
自然迭代器:
// C++ Random Access iterators
++it ; // move to the next item
--it ; // move to the previous item
it += 5 ; // move to the next 5th item (random access)
value = *it ; // gets the value of the current item
*it = 3.1415 ; // sets the value 3.1415 to the current item
(*it).foo() ; // call method foo() of the current item
// Java ListIterator<E> "bi-directional" iterators
value = it.next() ; // move to the next item & return the value
value = it.previous() ; // move to the previous item & return the value
it.set(3.1415) ; // sets the value 3.1415 to the current item
Natural functors:
自然函子:
// C++ Functors
myFunctorObject("Hello World", 42) ;
// Java Functors ???
myFunctorObject.execute("Hello World", 42) ;
Text concatenation:
文本串联:
// C++ stream handling (with the << operator)
stringStream << "Hello " << 25 << " World" ;
fileStream << "Hello " << 25 << " World" ;
outputStream << "Hello " << 25 << " World" ;
networkStream << "Hello " << 25 << " World" ;
anythingThatOverloadsShiftOperator << "Hello " << 25 << " World" ;
// Java concatenation
myStringBuffer.append("Hello ").append(25).append(" World") ;
Ok, in Java you can use MyString = "Hello " + 25 + " World" ;
too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???
好的,在 Java 中你也可以使用MyString = "Hello " + 25 + " World" ;
...但是,等一下:这是运算符重载,不是吗?不是骗人吗???
:-D
:-D
Generic code?
通用代码?
The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.
相同的通用代码修改操作数应该可用于内置/原语(在 Java 中没有接口)、标准对象(可能没有正确的接口)和用户定义的对象。
For example, calculating the average value of two values of arbitrary types:
例如,计算任意类型的两个值的平均值:
// C++ primitive/advanced types
template<typename T>
T getAverage(const T & p_lhs, const T & p_rhs)
{
return (p_lhs + p_rhs) / 2 ;
}
int intValue = getAverage(25, 42) ;
double doubleValue = getAverage(25.25, 42.42) ;
complex complexValue = getAverage(cA, cB) ; // cA, cB are complex
Matrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix
// Java primitive/advanced types
// It won't really work in Java, even with generics. Sorry.
Discussing operator overloading
讨论运算符重载
Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.
既然我们已经看到了使用运算符重载的 C++ 代码与 Java 中的相同代码之间的公平比较,我们现在可以将“运算符重载”作为一个概念来讨论。
Operator overloading existed since before computers
自计算机出现以来就存在运算符重载
Even outside of computer science, there is operator overloading: For example, in mathematics, operators like +
, -
, *
, etc. are overloaded.
甚至外部计算机科学的,存在操作者重载:例如,在数学,操作者喜欢+
,-
,*
等被过载。
Indeed, the signification of +
, -
, *
, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).
实际上,的意义+
,-
,*
等的变化取决于类型的操作数(数字,载体,量子波函数,矩阵等)。
Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?
我们大多数人,作为我们科学课程的一部分,根据操作数的类型学习了运算符的多种含义。我们有没有发现他们很困惑,他们?
Operator overloading depends on its operands
运算符重载取决于其操作数
This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.
这是运算符重载最重要的部分:就像在数学或物理学中一样,操作取决于其操作数的类型。
So, know the type of the operand, and you will know the effect of the operation.
所以,知道操作数的类型,你就会知道操作的效果。
Even C and Java have (hard-coded) operator overloading
甚至 C 和 Java 也有(硬编码)运算符重载
In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).
在 C 中,运算符的实际行为将根据其操作数而改变。例如,添加两个整数与添加两个双精度数,甚至一个整数和一个双精度数不同。甚至还有整个指针算术域(无需强制转换,您可以向指针添加一个整数,但不能添加两个指针......)。
In Java, there is no pointer arithmetic, but someone still found string concatenation without the +
operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.
在 Java 中,没有指针算法,但仍然有人发现没有+
运算符的字符串连接是荒谬的,足以证明“运算符重载是邪恶的”信条中的异常是合理的。
It's just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can't provide your own.
只是您作为 C(出于历史原因)或 Java(出于个人原因,见下文)编码器,您无法提供自己的编码器。
In C++, operator overloading is not optional...
在 C++ 中,运算符重载不是可选的...
In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-definedtypes can have user-definedoperator overloads.
在 C++ 中,内置类型的运算符重载是不可能的(这是一件好事),但用户定义的类型可以具有用户定义的运算符重载。
As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.
如前所述,在 C++ 中,与 Java 相反,与内置类型相比,用户类型不被视为该语言的二等公民。因此,如果内置类型具有运算符,则用户类型也应该能够拥有它们。
The truth is that, like the toString()
, clone()
, equals()
methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.
事实是,就像toString()
, clone()
,equals()
方法适用于 Java(即类标准),C++ 运算符重载是 C++ 的重要组成部分,以至于它变得与原始 C 运算符或前面提到的 Java 方法一样自然。
Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.
结合模板编程,运算符重载成为众所周知的设计模式。事实上,如果不使用重载运算符和为您自己的类重载运算符,您就无法在 STL 中走得很远。
...but it should not be abused
...但它不应该被滥用
Operator overloading should strive to respect the semantics of the operator. Do not subtract in a +
operator (as in "do not subtract in a add
function", or "return crap in a clone
method").
运算符重载应该努力尊重运算符的语义。不要在+
运算符中减去(如“不要在add
函数中减去”或“在clone
方法中返回废话”)。
Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for &&
and ||
, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators &&
and ||
enjoy.
演员超载可能非常危险,因为它们会导致歧义。因此,它们应该真正保留用于定义明确的案例。至于&&
and ||
,除非您真的知道自己在做什么,否则永远不要重载它们,因为您将失去本机运算符&&
和||
享受的短路评估。
So... Ok... Then why it is not possible in Java?
所以......好吧......那为什么它在Java中是不可能的?
Because James Gosling said so:
因为詹姆斯高斯林是这么说的:
I left out operator overloading as a fairly personal choicebecause I had seen too many people abuse it in C++.
James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm
我忽略了运算符重载作为一个相当个人的选择,因为我看到太多人在 C++ 中滥用它。
詹姆斯·高斯林。资料来源:http: //www.gotw.ca/publications/c_family_interview.htm
Please compare Gosling's text above with Stroustrup's below:
请比较上面 Gosling 的文字和下面 Stroustrup 的文字:
Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because I did not think I had the right to force my views on others.
Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)
许多C ++的设计决策有他们在我的厌恶根迫使人们做的事情在一些特殊的方式[...]通常情况下,我很想取缔一个功能,我个人不喜欢,我没有这样做,因为我不认为我有将我的观点强加于他人的权利。
比亚恩·斯特劳斯特鲁普。来源:C++ 的设计与演进(1.3 一般背景)
Would operator overloading benefit Java?
运算符重载对 Java 有益吗?
Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).
某些对象将极大地受益于运算符重载(具体或数字类型,如 BigDecimal、复数、矩阵、容器、迭代器、比较器、解析器等)。
In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's personal choice.
在 C++ 中,由于 Stroustrup 的谦逊,您可以从这个好处中受益。在 Java 中,您只是因为 Gosling 的个人选择而被搞砸了。
Could it be added to Java?
它可以添加到Java中吗?
The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..
现在不在 Java 中添加运算符重载的原因可能是内部、对该功能的过敏、对开发人员的不信任(你知道,似乎困扰着 Java 团队的破坏者......)、与以前的 JVM 的兼容性,编写正确规范的时间等。
So don't hold your breath waiting for this feature...
所以不要屏住呼吸等待这个功能......
But they do it in C#!!!
但是他们在 C# 中做到了!!!
Yeah...
是的...
While this is far from being the only difference between the two languages, this one never fails to amuse me.
虽然这远不是两种语言之间的唯一区别,但这一区别总是让我感到很开心。
Apparently, the C# folks, with their "every primitive is a struct
, and a struct
derives from Object", got it right at first try.
显然,C# 人,他们的“每个原语都是 a struct
, astruct
派生自 Object”,第一次尝试就做对了。
And they do it in other languages!!!
他们用其他语言做它!
Despite all the FUD against used defined operator overloading, the following languages support it: Scala, Dart, Python, F#, C#, D, Algol 68, Smalltalk, Groovy, Perl 6, C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran 90, Swift, Ada, Delphi 2005...
尽管所有 FUD 都反对使用定义的运算符重载,但以下语言支持它:Scala、Dart、Python、F#、C#、D、Algol 68、Smalltalk、Groovy、Perl 6、C++、Ruby、Haskell、MATLAB、Eiffel、Lua、Clojure、Fortran 90、Swift、Ada、Delphi 2005...
So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.
这么多语言,这么多不同(有时是对立的)哲学,但他们都同意这一点。
Food for thought...
深思熟虑...