Retro video games delivered to your door every month!
Click above to get retro games delivered to your door ever month!
X-Hacker.org- Zortech C++ Language Reference - streams: output of user defined types http://www.X-Hacker.org [<<Previous Entry] [^^Up^^] [Next Entry>>] [Menu] [About The Guide]
   Streams: Output of User Defined Types
   Overloading  operator<<  for user defined  types  is  straightforward.
   Consider an arbitrary class Triplet:

   #include <stream.hpp>

   class Triplet {
   int t1, t2, t3;
   public:
   Triplet() { t1 = t2 = t3 = 0; }
   Triplet(int a, int b, int c)
   { t1 = a; t2 = b; t3 = c; }
   friend ostream&
   operator<<(ostream&, Triplet&);
   };
   class  Triplet declares an appropriate overloaded operator<<  function
   to be a friend. The implementation is then:

   ostream&
   operator<<(ostream& os, Triplet& tr)
   {
        os << tr.t1 << ": " << tr.t2 << ": " << tr.t3;
        return os;
   }

   Which is used just like any other type.
   main()
   {
   Triplet t(3,4,5);
   cout << t;
   }

   The operator void* function is provided so that an ostream object  can
   be  tested  directly. Using the conversion to a void pointer  is  less
   likely to result in accidental ambiguities than is a cast to  integer.
   The conversion allows expressions like:

   int *ip;
   while (cout << *ip++)

   The  use of operator! does not give the same scope for  ambiguity.  It
   can return an integer.

   The  function  rdstate allows the state flags to be  read  explicitly,
   while  clear can be used to set the flags to any required  value.  Its
   integer argument is defaulted to zero to correspond to its most common
   use, clearing the error flags in an attempt to continue the  operation
   in progress.

   A  final  access  function sbuffer, returns a pointer  to  the  buffer
   associated with the ostream.


Online resources provided by: http://www.X-Hacker.org --- NG 2 HTML conversion by Dave Pearson