Is there a way to overload the <operator, as a member of a class, to print the values as a text stream. For instance:
class TestClass { public: ostream& operator<<(ostream& os) { return os << "I'm in the class, msg=" << msg << endl; } private: string msg; }; int main(int argc, char** argv) { TestClass obj = TestClass(); cout << obj; return 0; }
The only way I could think of is to overload the statement outside the class:
ostream& operator<<(ostream& os, TestClass& obj) { return os << "I'm outside of the class and can't access msg" << endl; }
But then the only way to access the private parts of the property would be through friendship with an operator function, and I would rather avoid friends if possible, and thus ask you for alternative solutions.
Any comments or recommendations on how to proceed would be helpful :)
source share