What is the difference between Java's equals() and C++'s operator ==?

牧云@^-^@ 提交于 2019-12-04 02:22:32

In Java, all types ultimately derive from Object, and Object defines a virtual function Object.equals(Object other), so you can compare anything with anything else, regardless of whether it makes sense or not. In C++, there is no univeral base, and there is no implicit definition of ==. == is normally only overridden when it makes sense, for comparing objects of the same type, and the compiler will complain if you write nonsense code. In cases where there is an inheritance hierarchy, it is, of course, up to the author to decide whether == makes sense (I usually doesn't, but there are a lot of exceptions), and if so, what it should mean with respect to comparing objects of different types. Within the hierarchy, or outside of it: it might make sense to support == between BigInteger and BigFloat, for example, even if the classes aren't related by inheritance.

The reason you don't see the problem discussed much in C++ is, of course, because you don't define == unless there's some logical meaning for it, and then you define it according to the logical meaning. In Java, you generally have to define equals regardless, so you have to "invent" some meaning, and you get discussion over what the invented meaning should be.

An obvious difference is that Java equals is a virtual method (since all Java methods are by default), so will do dynamic dispatch based on its target.

C++ operator== overloads are statically resolved, but it's easy to delegate to a virtual function if you want polymorphic behavior.

Except for the difference in polymorphism, all other behavior is completely up to the implementer of the particular type (or in the C++ case, the implementer of a freestanding operator==).

Java has a single base-type for all reference types -- all reference types extend java.lang.Object (modulo null which breaks equals symmetry since (null).equals(...) is an error).

So you can say in Java "do these two java references point to equivalent things?" without knowing anything about the types of the references, so Java has a place to hang an equals(Object) method of its base reference type, java.lang.Object in a way that C++ does not. In C++ there is no such base-type so you have a multitude of different == operator and the compiler has to be able to figure out statically which to use.

Since Java objects always carry RTTI and all dispatch to an instance method is speced as virtual, there are things you can do with reflection when defining equivalence classes in code that you simply cannot with C++ objects.

Making C++ == equivalent to Java's equals assumes that you've overridden the == operator to do "deep equals" in C++ and the Java "equals" to do the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!