Is there a way to overload the << operator, as a class member, to print values as a text stream. Such as:
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 was to overload the operator outside of 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 object would be to friend the operator function, and I’d rather avoid friends if possible and thus ask you for alternative solutions.
Any comments or recommendations on how to proceed would be helpful 🙂
You have stumbled across the canonical way to implement this functionality. What you have is correct.