超载'=='让你'!='? [英] Does overloading '==' get you '!='?

查看:129
本文介绍了超载'=='让你'!='?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我为结构手动重载 == 运算符,那么我可以免费获得!= (可能定义为布尔相反),或者我必须手动重载它(即使只是 return!(this == rhs)

If I manually overload the == operator for a structure, do I get the != operator for free (presumably defined to be the boolean opposite), or do I have to overload it manually (even if to just return !(this == rhs)?

编辑 - 问题不是我是否可以重载两个运算符,但是如果我已经重载了等于运算符,我是否必须重载不等式。无论如何,给出了好的答案。 / p>

Edit-The question is not whether or not I CAN overload both operators, but whether I must overload inequality if I've already overloaded the equality operator. Regardless, good answers have been given.

推荐答案

重载运算符== 不会给您 operator!= 。你必须手动执行它,并且规范的方式是以 operator == $ c>!(left == right)。

Overloading operator == does not give you operator !=. You have to do it manually and the canonical way is to implement it in terms of operator == as in !(left == right).

运算符的语义不是由标准决定的, operator == 表示等于重载 operator!= 不是这是一个好的做法,实际上应该劝阻。

The semantics of the operators are not dictated by the standard. You could very well overload operator == to mean equality yet overload operator != to something different like addition or even equality again (not that this is a good practice, in fact it should be discouraged. When in doubt, do as the ints do...).[Refer (1) Below]

在旁注中, Boost.Operators 可以帮助您为操作符提供规范的实现。还有 std :: rel_ops ,具有 operator!= 的规范实现。

On a side note, Boost.Operators can help you provide canonical implementations for operators. There is also std::rel_ops with a canonical implementation for operator !=.

(1)要了解详情,请阅读 操作员的三个基本规则在C ++中重载

(1) To know more about it read Three basic rules of operator overloading in C++.

这篇关于超载'=='让你'!='?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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