일상 코딩
[C++/9.08] 형변환 오버로딩 typecast overloading 본문
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
    
    
  'C++ > 따배C++ 09강 연산자 오버로딩' 카테고리의 다른 글
| [C++/9.10] 변환 생성자, explicit, delete (0) | 2021.10.31 | 
|---|---|
| [C++/9.09] 복사 생성자, 복사 초기화 반환값 최적화 (0) | 2021.10.31 | 
| [C++/9.07] 괄호"()" 연산자 오버로딩과 함수 객체 Functor (1) | 2021.10.30 | 
| [C++/9.06] 첨자"[]" 연산자 오버로딩 (0) | 2021.10.30 | 
| [C++/9.05] 증감 연산자 오버로딩 (0) | 2021.10.29 |