C ++重载操作符==和< [英] C++ overloading operators difference between == and <

查看:110
本文介绍了C ++重载操作符==和<的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下我们的过载 == < 之间有什么区别吗?

$例如,如果我使用一个映射:

  map< Type,int>一个(); 

friend bool operator<(const Type& lhs,const Type& rhs);

friend bool operator ==(const Type& lhs,const Type& rhs);

当我调用时,我实现了两个运算符:

  a.find(value); 

== 的运算符函数称为?我想不是。我调试,看到< 被调用,但为什么? <



的操作符函数的行为应该是什么?



谢谢。

运算符重载 == 没有其他); 运算符<
重载< 运算符(且无其他)。



std :: map 定义为使用 std :: less code> std :: less )由
默认值和 std :: less 定义为使用< 。一般来说,
不过,我建议重载运算符<,除非
有序比较对您的类有意义,在这种情况下,你应该
以一致的方式重载所有六个比较运算符。
否则,您可以指定一个比较函数类型作为 std :: map 的附加
模板参数;比较功能对象应该
定义严格的弱排序关系。如果类型被设计为
用作键,但排序仍然是纯任意的,你可能
specialize std :: less



对于Java,没有操作符重载,显然不能使用< ;
默认情况下, SortedMap (等效于 std :: map 的Java)需要
然而,这又需要一个比较
函数,它返回一个值< == > 0,取决于
/ code>是< == > 比其他。我承认我发现这个
有点更合乎逻辑,但差别是非常,非常小。 (C ++的决定背后的
理由是内置类型如 int
double 可以用作键,在Java中,您必须将它们加以封装。)


Could anybody explain me what is the difference between overload == and <?

For example, if I use a map:

map<Type, int> a();

friend bool operator<(const Type& lhs, const Type& rhs);

friend bool operator==(const Type& lhs, const Type& rhs);

And I implement both operators, when I call:

a.find(value);

The operator function of == is being called? I think not. I debugged and saw that < is called, but why? What should be the behavior of the operator function of <?

I come from Java where the method equals is called and is pretty simple to understand the behavior.

Thanks.

解决方案

operator== overloads the == operator (and no other); operator< overloads the < operator (and no other).

std::map is defined to use std::less (and only std::less) by default, and std::less is defined to use < by default. In general, however, I would recommend not overloading operator< unless ordered comparison makes sense for your class, in which case, you should overload all six comparison operators, in a coherent fashion. Otherwise, you can specify a comparison functional type as an additional template argument to std::map; the comparison functional object should define a strict weak ordering relationship. If the type is designed to be used as a key, but the ordering is still purely arbitrary, you might specialize std::less.

As for Java, without operator overloading, it obviously can't use <; by default, SortedMap (the Java equivalent to std::map) requires the keys to be Comparable, however, which in turn requires a compare function, which returns a value <, == or > 0, depending on whether this is <, == or > than other. I'll admit that I find this a little bit more logical, but the difference is very, very small. (The rationale behind the C++ decision is that build-in types like int or double can be used as keys. In Java, you'ld have to box them.)

这篇关于C ++重载操作符==和&lt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆