首页 > 解决方案 > 将“operator>”委托给“operator<”是不好的形式吗?

问题描述

我在最近的一个程序中写了这个:

friend bool operator<(const MyClass& a, const MyClass& b) {
    // Lots of comparison code here
}

friend bool operator>(const MyClass& a, const MyClass& b) {
    return b < a;
}

当我运行程序时它工作正常,但这是不好的形式吗?有什么理由我不应该这样做吗?或者有什么我应该做的吗?

通常我会写operator<operator>完全分开,但是因为里面的代码operator<很长,我决定走这条捷径。

另请注意,速度在此程序中至关重要。

标签: c++operator-overloading

解决方案


为了避免反复(或复制/粘贴)编写相同的代码,这是常见的错误来源:

bool operator<(const Foo& a, const Foo& b) {
    //Actual comparison of members
}

bool operator>=(const Foo& a, const Foo& b) {
    return !(a < b);
}

bool operator>(const Foo& a, const Foo& b) {
    return b < a;
}

bool operator<=(const Foo& a, const Foo& b) {
    return !(b < a); //Can also do !(a > b)
}

问题来了,相等可以用小于来定义,但如果你需要严格的弱排序,它意味着与显式相等不同的东西:

bool operator==(const Foo& a, const Foo& b) {
    return !(a < b) && !(b < a);
}

bool operator!=(const Foo& a, const Foo& b) {
    return !(a == b);
}

或者

bool operator==(const Foo& a, const Foo& b) {
    //Actual comparison of members.
}

bool operator!=(const Foo& a, const Foo& b) {
    return !(a == b);
}

推荐阅读