250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/9.08] 형변환 오버로딩 typecast overloading 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.08] 형변환 오버로딩 typecast overloading

polarcompass 2021. 10. 30. 11:06
728x90
#include<iostream>
using namespace std;

class Cents
{
private:
    int m_cents;

public:
    Cents(int cents = 0)
    {
        m_cents = cents;
    }
    
    int getCents() 
    {
        return m_cents;
    }

    void setCents(int cents)
    {
        m_cents = cents;
    }

    operator int()
    {
        cout << "cast here" << endl;
        return m_cents;
    }
};

void printInt(const int &value)
{
    cout << value << endl;
}

class Dollar
{
private:
    int m_dollars = 0;

public:
   Dollar(const int& input): m_dollars(input) {}
   
   operator Cents()
   {
       return Cents(m_dollars * 100);
   }
};

int main()
{
    // Cents cents{7};
    // int value = (int)cents;
    // value = int(cents);
    // value = static_cast<int>(cents);

    // printInt(cents);

    Dollar dol(2);

    Cents cents = dol;

    printInt(cents);

    return 0;
}
728x90