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

형변환 오버로딩 (Typecasts Overloading)

  • (int)객체, int(객체), static_cast<int>(객체) 등의 형태로 형변환을 할 수 있게 해준다.

  • 묵시적 형변환도 가능해진다.


예제

  #include <iostream>

  class Cents
  {
    int cents_;

  public:
    Cents(int cents = 0) { cents_ = cents; }

    operator int()
    {
      std::cout << "cast here" << std::endl;
      return cents_;
    }
  };

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

  int        main()
  {
    using namespace std;

    Cents    cents(7);

    printInt(cents);

    int value;

    value = (int)cents;
    value = int(cents);
    value = static_cast<int>(cents);
  }

  /* stdout
  cast here
  7
  cast here
  cast here
  cast here
  */
  • 다른 객체로의 형변환 오버로딩도 가능하다.

    #include <iostream>
    
    class Cents
    {
      int cents_ = 0;
    
    public:
      Cents(const int& cents = 0) { cents_ = cents; }
    
      operator int()
      {
        std::cout << "cast here" << std::endl;
        return cents_;
      }
    };
    
    class Dollars
    {
      int    dollars_ = 0;
    
    public:
      Dollars(const int& dollars = 0) { dollars_ = dollars; }
    
      operator Cents()
      {
        return Cents(dollars_ * 100);
      }
    };
    
    void    printInt(const int& value)
    {
      std::cout << value << std::endl;
    }
    
    int        main()
    {
      using namespace std;
    
      Dollars    dol(2);
      Cents    cents(dol);
    
      printInt(cents);
    }
    
    /* stdout
    cast here
    200
    */