operator在java中是什么意思,Java的equals()和C ++的operator ==有什么区别?

In a question regarding the use of typeid is C++, I suggested it could be used to compare types in objects comparison. I haven't seen it done much, but I had Java's equals in mind.

Looking into Java a bit more, this seems to be the case: Some say the actual classes of the two objects should be compared, and some say instanceof is the right tool to use, possibly with double dispatch. There are of course cases in which one of the two is definitively more suitable, but at least both options are considered.

In C++, OTOH, I could barely find code in which the actual types are compared. On most cases, double dispatch is used (with dynamic_cast), and I couldn't find anyone insisting a quick type comparison is the right thing to do at the beginning of the equality check.

I'm wondering why the problem of polymorphic type comparison has two acceptable solutions in Java, while in C++ only one seems to be considered the best practice? Are there significant technical differences, or just different approaches?

Note: My claims are based on impression, not concrete knowledge. If they are wrong and Java and C++ are indeed similar in that aspect - or different for reasons other than the above, it will obviously be an acceptable answer.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值