3

提供された整数のサイズに応じて、適切にフォーマットされた16 進数を書き込めるカスタムI/O マニピュレータを C++ で作成しようとしています。0xFFFF

例えば:

  • char c = 1になる0x01
  • short s = 1になる0x0001

等々。ガベージを印刷しているコードでエラーが見つかりません:

#include <iostream>
#include <iomanip>


class hexa_s
{
   mutable std::ostream *_out;

   template<typename T>
   const hexa_s& operator << (const T & data) const
   {
       *_out << std::internal << std::setfill( '0' ) << std::hex << std::showbase << std::setw( sizeof( T ) * 2 ) << data;

       return *this;
   }

   friend const hexa_s& operator <<( std::ostream& out, const hexa_s& b )
   {
       b._out = &out;
       return b;
   }
};

hexa_s hexa( )
{
    return hexa_s( );
}


int main()
{
    int value = 4;

    std::cout << hexa << value << std::endl;

    return 0;
}
4

2 に答える 2