c++ - 将“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<
很长,我决定走这条捷径。
另请注意,速度在此程序中至关重要。
解决方案
为了避免反复(或复制/粘贴)编写相同的代码,这是常见的错误来源:
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);
}
推荐阅读
- python - 有没有办法两次使用随机链接?即像维基百科随机文章生成器,但用于不同的站点
- pandas - 两个数据帧的逻辑“或”
- javascript - i.eaao是什么编码
- windows - 可以在 VPS 上运行 Docker Desktop for Windows 吗?
- javascript - 如何仅对一个测试套件使用手动模拟?
- python - 'DataFrame' 对象没有属性 'global_mean'
- mongodb - 如何通过 MongoDb 中的嵌套对象字段加入集合?
- asp.net - 如何使用旧版本的实体框架从头开始创建 ASP.NET 项目?
- sql - Azure MSSQL - 将 nvarchar 数据类型转换为 datetime 数据类型导致值超出范围
- python - Python Pandas 当我在现有数据框中添加一列时,我的新列不正确