比较运算符重载 [英] Comparison operator overloading
本文介绍了比较运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最佳做法(在这种情况下):
Which is best practice (in this case):
bool Foo::operator==(const Foo& other) {
return bar == other.bar;
}
// Implementation 1
bool Foo::operator!=(const Foo& other) {
return bar != other.bar
}
// Implementation 2
bool Foo::operator!=(const Foo& other) {
return !(*this == other);
}
对于>,<,< =,> =之类的运算符,我会尽可能采用实现2.但是,对于!=,我认为实现1更好,因为没有进行其他方法调用,这是正确的吗?
For operators like >, <, <=, >= I would go with implementation 2 when possible. However, for != I think implementation 1 is better since another method call is not made, is this correct?
推荐答案
第二个实现具有显着的约束,即==
始终是与!=
相对的布尔值.这可能就是您想要的,并且它使您的代码更易于维护,因为您只需更改一个实现即可使两者保持同步.
The second implementation has the notable constraint that ==
will always be the boolean opposite of !=
. This is probably what you want, and it makes your code easier to maintain because you only have to change one implementation to keep the two in sync.
这篇关于比较运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文