[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppOverloadStreamOut

(C++) Overloading the stream out operator, <<

Overloading can be done by making it a free function or a method. Overload it with a free function [1], see method for guideline.

A two-dimensional std::vector

template <class T>
std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T> >& stlImage)
{
  const int maxx = stlImage.size();
  if (maxx == 0)
  {
    os << "{empty image}";
  }
  else
  {
    const int maxy = stlImage[0].size();
    for (int y=0; y!=maxy; ++y)
    {
      assert(maxy == static_cast<int>(stlImage[y].size()); //Assume it is a rectangular 2D vector
      for (int x=0; x!=maxx; ++x)
      {
        os  << static_cast<int>(stlImage[x][y]);
      }
      os << '\n';
    }
  }
  return os;
}

int main()
{
  const std::vector<std::vector<unsigned char> > image(20,std::vector<unsigned char>(10,127));
  std::cout << std::hex << image << std::dec << '\n';
}


A custom class

  1. include <iostream>
struct MyClass { MyClass() : mValue(0) {} int mValue; }; std::ostream& operator<<(std::ostream& os, const MyClass& myClass) { os << "MyClass.value: " << myClass.mValue; return os; } int main() { MyClass myClass; myClass.mValue = 1; std::cout << myClass << std::endl; }


However, this code works only on statically allocated instances of MyClass. To be also able to cout pointers and auto_ptr's, you could easily expand the code to:

  1. include <iostream>
  2. include <memory>
struct MyClass { MyClass() : mValue(0) {} int mValue; }; std::ostream& operator<<(std::ostream& os, const MyClass& myClass) { os << "MyClass.value: " << myClass.mValue; return os; } std::ostream& operator<<(std::ostream& os, const MyClass* const myClass) { os << *myClass; return os; } std::ostream& operator<<(std::ostream& os, const std::auto_ptr<MyClass>& myClass) { os << myClass.get(); return os; } int main() { { MyClass myClass; myClass.mValue = 1; std::cout << myClass << std::endl; } { MyClass * myClass = new MyClass; myClass->mValue = 2; std::cout << myClass << std::endl; delete myClass; } { std::auto_ptr<MyClass> myClass(new MyClass); myClass->mValue = 3; std::cout << myClass << std::endl; } }


Reference



last edited (December 24, 2006) by bilderbikkel, Number of views: 3697, Current Rev: 10 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.