C++ Code Snippet - Making a Custom Class ostream Outputable
Posted on 2007-03-01 14:47 by Timo Bingmann at Permlink with 1 Comments. Tags: #c++ #code-snippet
How to get a custom class to work with std::cout << obj;
? I for my part always forget the exact prototype of the required operator<<
. Here is an minimal working example to copy code from:
#include <iostream> struct myclass { int a, b; myclass(int _a, int _b) : a(_a), b(_b) { } }; // make myclass ostream outputtable std::ostream& operator<< (std::ostream &stream, const myclass &obj) { return stream << "(" << obj.a << "," << obj.b << ")"; } int main() { myclass obj(42, 46); std::cout << obj << std::endl; }
it is perhaps better to make a pass-thru template to avoid most of the typing:
With the template version, all you need to is: