ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

深入理解C++ 重载 <二十二>,<,>=,<=运算符

深入理解C++ 重载 <二十二>,<,>=,<=运算符 C 中,,,都属于关系运算符都是二元运算符通常返回bool。它们既可以重载为成员函数也可以重载为非成员函数。1. 基本语法成员函数版本cppbool operator(const T other) const; bool operator(const T other) const; bool operator(const T other) const; bool operator(const T other) const;非成员函数版本cppbool operator(const T lhs, const T rhs); bool operator(const T lhs, const T rhs); bool operator(const T lhs, const T rhs); bool operator(const T lhs, const T rhs);一般要求返回bool参数用const T避免拷贝成员函数末尾加const表示不修改当前对象逻辑必须一致例如a b为真时a b必须为假通常先实现和然后基于它们实现其他关系运算符。2. 推荐实现关系如果已经定义了operator和operator那么可以这样实现cppa b 等价于 b a a b 等价于 !(b a) a b 等价于 !(a b)或者cppa b 等价于 a b || a b a b 等价于 a b || a b这样做可以保证逻辑一致避免重复写比较逻辑。#include iostream class Point { private: int x_; int y_; public: Point(int x 0, int y 0) : x_(x), y_(y) {} // 相等 bool operator(const Point other) const { return x_ other.x_ y_ other.y_; } // 小于先比 x再比 y bool operator(const Point other) const { if (x_ ! other.x_) { return x_ other.x_; } return y_ other.y_; } // 大于等价于 other *this bool operator(const Point other) const { return other *this; } // 小于等于等价于 !(other *this) bool operator(const Point other) const { return !(other *this); } // 大于等于等价于 !(*this other) bool operator(const Point other) const { return !(*this other); } // 方便输出 friend std::ostream operator(std::ostream os, const Point p) { return os ( p.x_ , p.y_ ); } }; int main() { Point a(1, 2); Point b(1, 3); Point c(2, 0); Point d(1, 2); std::cout std::boolalpha; std::cout a a , b b , c c , d d \n; std::cout a b: (a b) \n; // true std::cout a b: (a b) \n; // false std::cout a d: (a d) \n; // true std::cout a d: (a d) \n; // true std::cout c a: (c a) \n; // true return 0; }
返回列表