C++/Overloading 2021. 3. 16. 00:25

비교 연산자 오버로딩 (Comparison Operator Overloading)

  • if문, std::sort 등을 사용하려면 필수적으로 구현해야 한다.

예제

  • ==, != 오버로딩 예제

    #include <iostream>
    
    class Cents
    {
      int    cents_;
    
    public:
      Cents(int cents = 0) { cents_ = cents; }
    
      bool operator == (Cents& c)
      {
        return (cents_ == c.cents_);
      }
    
      bool operator != (Cents& c)
      {
        return (cents_ != c.cents_);
      }
    
      friend std::ostream& operator << (std::ostream& out, const Cents& cents)
      {
        out << cents.cents_;
        return (out);
      }
    };
    
    int        main()
    {
      using namespace std;
    
      Cents    c1{ 6 };
      Cents    c2{ 6 };
      Cents    c3{ 0 };
    
      cout << std::boolalpha;
      cout << (c1 == c2) << endl;
      cout << (c1 != c2) << endl;
      cout << (c1 == c3) << endl;
      cout << (c1 != c3) << endl;
    }
    
    /* stdout
    true
    false
    false
    true
    */
  • < 오버로딩 예제

    • std::sort 함수를 사용하려면 < 연산자를 오버로딩해야 한다.
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    class Cents
    {
      int    cents_;
    
    public:
      Cents(int cents = 0) { cents_ = cents; }
      int& getCents() { return cents_; }
    
      bool    operator < (const Cents& c)
      {
        return (cents_ < c.cents_);
      }
    
      friend std::ostream& operator << (std::ostream& out, const Cents& cents)
      {
        out << cents.cents_;
        return (out);
      }
    };
    
    int        main()
    {
      using namespace std;
    
      vector<Cents>    arr(20);
    
      for (size_t i = 0; i < 20; ++i)
        arr[i].getCents() = i;
    
      std::random_shuffle(begin(arr), end(arr));
    
      for (auto& e : arr)
        cout << e << ' ';
      cout << endl;
    
      std::sort(begin(arr), end(arr));
    
      for (auto& e : arr)
        cout << e << ' ';
      cout << endl;
    }
    
    /* stdout
    12 1 9 2 0 11 7 19 4 15 18 5 14 13 10 16 6 3 8 17
    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    */