[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppOverloadStreamOut
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:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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
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; }
- include <iostream>
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:
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; } }
- include <iostream>
- include <memory>
Reference
- 1) Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2. Item 20: Class mechanics.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
