IT 관련자료/C++

비교연산자 오버로딩

elkein 2022. 3. 3. 19:23

전체코드

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Cents
{
private:
    int _cents;

public:
    Cents(int cents = 0) { _cents = cents; }
    int getCents() const { return _cents; }
    int& getCents() { return _cents; }

    //std::sort를 구현할 때는 (>) 이거 말고 (<) 이걸 구현해야함 ㅋㅋ;;;
    friend bool operator < (const Cents c1, const Cents c2)
    {
        return c1._cents < c2._cents;
    }

    //이렇게 오퍼레이터 오버로딩을 해준다면 !!! Centsㅌ 타입에서는 사용가능!! 
    friend bool operator == (const Cents& c1, const Cents& c2)
    {
        return c1._cents == c2._cents;
    }

    friend std::ostream& operator << (std::ostream& out, const Cents& cents)
    {
        out << cents._cents;
        return out;
    }
};

int main()
{
    vector<Cents> arr(20);
    for (unsigned i = 0; i < 20; ++i)
        arr[i].getCents() = i;

    std::random_shuffle(begin(arr), end(arr));

    for (auto& e : arr)
        cout << e << " ";
    cout << endl;

    //sort하려했는데 비교연산자가 오버로딩 되어있지 않아서 작동하지 않음
    std::sort(begin(arr), end(arr));
    
    for (auto& e : arr)
        cout << e << " ";
    cout << endl;




    int a = 3, b = 3;
    //여기서 a==b연산이 되는게 당연함...!
    if (a == b)
        cout << "Equal" << endl;

    Cents cents1(6);
    Cents cents2(6);

    //하지만 user defined type에서 비교했을때 연산자 작용 XX
    if (cents1 == cents2)
        cout << "Equal" << endl;


    cout << std::boolalpha;

    

    return 0;
}

 

 

user defined type에서 std::sort 사용시 문제발생 해결법

int main()
{
    vector<Cents> arr(20);
    for (unsigned i = 0; i < 20; ++i)
        arr[i].getCents() = i;

    std::random_shuffle(begin(arr), end(arr));

    for (auto& e : arr)
        cout << e << " ";
    cout << endl;

    //sort하려했는데 비교연산자가 오버로딩 되어있지 않아서 작동하지 않음
    std::sort(begin(arr), end(arr));
    
    for (auto& e : arr)
        cout << e << " ";
    cout << endl;

}

위와같은 오류가 발생

class Cents
{
private:
    int _cents;

public:
    Cents(int cents = 0) { _cents = cents; }
    int getCents() const { return _cents; }
    int& getCents() { return _cents; }

    //std::sort를 구현할 때는 (>) 이거 말고 (<) 이걸 구현해야함 ㅋㅋ;;;
    friend bool operator < (const Cents c1, const Cents c2)
    {
        return c1._cents < c2._cents;
    }
}

위와같이 비교연산자 오버로딩하면 오류없이 sort가 잘 됩니당