【发布时间】:2011-06-07 17:44:13
【问题描述】:
我目前正在查看一个旧的 C++ 代码库,发现很多代码是这样的:
bool SomeClass::operator==( const SomeClass& other ) const
{
return member1 == other.member1 && member2 == other.member2;
}
bool SomeClass::operator!=( const SomeClass& other ) const
{
return member1 != other.member1 || member2 != other.member2;
}
很明显,比较逻辑是重复的,上面的代码可能需要在两个地方而不是一个地方进行更改。
AFAIK 实现operator!= 的典型方式是这样的:
bool SomeClass::operator!=( const SomeClass& other ) const
{
return !( *this == other );
}
在后一种情况下,无论operator== 发生什么逻辑变化,它都会自动反映在operator!= 中,因为它只是调用operator== 并执行否定。
除了在 C++ 代码中重用 operator== 之外,是否应该以任何其他方式实现 operator!=?
【问题讨论】:
-
同样,应该尝试以最少冗余的方式实现
>, >=, <=, <运算符。 -
规则不应该是绝对的。所有规则普遍适用。但我相信总会有特定的情况,他们没有。但是想出一个(除非你昨天碰巧做到了)通常是不可能的(因为它们是规则的例外)。就像问的都是白天鹅。是的,所有天鹅都是白色的(直到 1500 年在澳大利亚发现黑天鹅)。 Ceaser: "rara avis in terris nigroque simillima cygno"
标签: c++ comparison operators operator-overloading