在这种情况下,最佳实践是什么:
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 更好,因为不需要进行另一方法调用,这个想法正确吗?
const
。此外,考虑使用自由函数而不是成员函数,因为前者在类型和转换方面对称,而后者则不是。如果你的类型可以从其他类型隐式转换,则这更加重要。 - David Rodríguez - dribeas