【发布时间】:2016-05-27 12:03:30
【问题描述】:
我想添加一个选项来对MyClass 的对象进行链式比较。例如:
MyClass one;
MyClass two;
MyClass three;
/*....*/
if (one == two == three){
/*....*/
}
因此,如果所有人都相等,它将返回true,否则将返回false。
我目前有这个运算符重载,在仅比较 MyClass 的两个实例时可以正常工作:
bool operator==(const MyClass &other);
我知道one==two==three 等于((one==two)==three),所以我想这应该将我的operator== 更改为:
MyClass& operator==(const MyClass &other);
但我无法理解如何完成此操作以便能够连续比较两个以上的实例(链接)。
【问题讨论】:
-
为什么不遵循正常语义并使用
if (one == two && two == three)? -
请不要。
-
@NathanOliver:确实,“EqualExpr”对象必须计算所有等式,而普通语义可能会短路。
-
“让它工作”是什么意思?
(one == two) == three在语义上不等同于one == two && two == three。 -
1) Principle of least astonishment。以奇怪和意想不到的方式做某事会导致用户体验/支持出现问题。 2) 提供一个具有实际帮助和不言自明的名称的辅助函数。编辑:回答此评论↓