I'm learning about operator overloading in C++, and I see that == and != are simply some special functions which can be customized for user-defined types. My concern is, though, why are there two separate definitions needed? I thought that if a == b is true, then a != b is automatically false, and vice versa, and there is no other possibility, because, by definition, a != b is !(a == b). And I couldn't imagine any situation in which this wasn't true. But perhaps my imagination is limited or I am ignorant of something?

我知道我可以用一个定义另一个,但这不是我要问的。我也没有问通过值和单位来比较对象之间的区别。或者两个对象是否可以同时相等和不相等(这绝对不是一个选项!这些事情是相互排斥的)。我想问的是:

有没有可能在这种情况下,问两个对象是否相等的问题是有意义的,但问它们不相等的问题是没有意义的?(无论是从用户的角度,还是从实现者的角度)

如果没有这种可能性,那么究竟为什么c++将这两个操作符定义为两个不同的函数呢?


当前回答

如果==和!=操作符实际上并不意味着相等,就像<<和>>流操作符并不意味着位移位一样。如果你把这些符号当作其他概念来对待,它们就不必相互排斥。

就相等而言,如果您的用例保证将对象视为不可比较的,那么每次比较都应该返回false(或者如果操作符返回非bool类型,则返回不可比较的结果类型),那么这样做是有意义的。我想不出一个具体的情况,这将是必要的,但我可以看到它是足够合理的。

其他回答

通过自定义操作符的行为,您可以使它们按照您的要求进行操作。

你可能希望自定义一些东西。例如,您可能希望自定义一个类。可以通过检查特定属性来比较该类的对象。了解了这种情况后,您可以编写一些只检查最小值的特定代码,而不是检查整个对象中每个属性的每一位。

Imagine a case where you can figure out that something is different just as fast, if not faster, than you can find out something is the same. Granted, once you figure out whether something is the same or different, then you can know the opposite simply by flipping a bit. However, flipping that bit is an extra operation. In some cases, when code gets re-executed a lot, saving one operation (multiplied by many times) can have an overall speed increase. (For instance, if you save one operation per pixel of a megapixel screen, then you've just saved a million operations. Multiplied by 60 screens per second, and you save even more operations.)

Hvd的回答提供了一些额外的例子。

也许是一个不可比较的规则,其中a != b为假,a == b为假,就像一个无状态位。

if( !(a == b || a != b) ){
    // Stateless
}

如果没有这种可能性,那么究竟为什么c++将这两个操作符定义为两个不同的函数呢?

因为你可以让它们超载,通过超载,你可以赋予它们一个与原来完全不同的含义。

例如,操作符<<,最初是位左移操作符,现在通常重载为插入操作符,如std::cout << something;和原来的意思完全不同。

因此,如果您接受重载操作符时操作符的含义会发生变化,那么就没有理由阻止user给operator ==赋予一个与operator !=不完全相反的含义,尽管这可能会令人困惑。

最后,使用这些操作符检查表达式a == b或a != b是否返回布尔值(true或false)。这些表达式在比较后返回一个布尔值,而不是互斥的。

是的,因为一个意思是“等价的”,另一个意思是“不等价的”,这两个术语是相互排斥的。此操作符的任何其他含义都是令人困惑的,应该无论如何避免。