重写大量的运算符函数非常浪费时间效率也不高,C++标准为了改善这些,封装了很多可用的接口函数,下面来看一下,重写一个类的比较操作符。
考虑到<,==,!=,>,<=,>=将要实现6个操作符,而真正需要实现的只有<和==两个,其他的四种都能通过这两个组合而成
struct Point {
int x; int y;
friend bool operator == (const Point& lhs, const Point& rhs) {
return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y);
}
friend bool operator < (const Point& lhs, const Point& rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
friend bool operator !=(const Point& lhs, const Point& rhs) {
return !(lhs == rhs);
}
friend bool operator > (const Point& lhs, const Point& rhs) {
return rhs < lhs;
}
friend bool operator <=(const Point& lhs, const Point& rhs) {
return !(lhs > rhs);
}
friend bool operator >=(const Point& lhs, const Point& rhs) {
return !(lhs < rhs);
}
};
主要的两个操作符,通过使用元组封装比较来实现,其他的四个可以根据这两个进行组合实现。
元组由C++17提供标准支持。
如果你的开发环境支持C++20,那么重载运算符将会变得非常简单。
struct Point {
int x; int y;
friend auto operator <=> (const Point& lhs, const Point& rhs) = default;
};
20提供了三路比较运算符,只需要声明一个就可以实现上面的六种运算符的功能。