作为成员函数重载

     class Point {
     public:
         int x;
         int y;
         Point(int a = 0, int b = 0) : x(a), y(b) {}
         bool operator<(const Point& other) const {
             if (x!= other.x) {
                 return x < other.x;
             } else {
                 return y < other.y;
             }
         }
         bool operator>(const Point& other) const {
             return other < *this;
         }
     };

作为全局函数重载(结合友元函数)

     class Point {
 public:
     int x;
     int y;
     Point(int a = 0, int b = 0) : x(a), y(b) {}
     friend bool operator&lt;(const Point&amp; p1, const Point&amp; p2);
     friend bool operator&gt;(const Point&amp; p1, const Point&amp; p2);
 };
 bool operator&lt;(const Point&amp; p1, const Point&amp; p2) {
     if (p1.x!= p2.x) {
         return p1.x &lt; p2.x;
     } else {
         return p1.y &lt; p2.y;
     }
 }
 bool operator&gt;(const Point&amp; p1, const Point&amp; p2) {
     return p2 &lt; p1;
 }</code></pre><p style=""><strong>在容器中使用重载的</strong><code>&lt;</code><strong>和</strong><code>&gt;</code><strong>运算符(以</strong><code>set</code><strong>容器为例)</strong></p><pre><code class="language-c++">     #include &lt;iostream&gt;
 #include &lt;set&gt;
 int main() {
     std::set&lt;Point&gt; s;
     s.insert(Point(1, 2));
     s.insert(Point(3, 4));
     s.insert(Point(1, 3));
     for (const auto&amp; p : s) {
         std::cout &lt;&lt; "(" &lt;&lt; p.x &lt;&lt; ", " &lt;&lt; p.y &lt;&lt; ")" &lt;&lt; std::endl;
     }
     return 0;
 }</code></pre><p style=""></p>

发表评论