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 :)
When overloading an operator using a member function: The overloaded operator must be added as a member function of the left operand. The left operand becomes the implicit *this object. All other operands become function parameters.
You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function.
By overloading the operators, we can give additional meaning to the operators like +-*/=.,= etc., which by default are supposed to work only on standard data types like int, float, char, void etc. It is an essential concept in C++.
The operator overloading in Python means provide extended meaning beyond their predefined operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class and "str" class.
It needs to be a non-member, since the class forms the second argument of the operator, not the first. If the output can be done using only the public interface, then you're done. If it needs access to non-public members, then you'll have to declare it a friend; that's what friends are for.
class TestClass {
public:
friend ostream& operator<<(ostream& os, TestClass const & tc) {
return os << "I'm a friend of the class, msg=" << tc.msg << endl;
}
private:
string msg;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With