Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Overloading operator<< for printing as a member
- 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;
- }
- ostream& operator<<(ostream& os, TestClass& obj) {
- return os << "I'm outside of the class and can't access msg" << endl;
- }
- 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;
- };
- class TestClass {
- public:
- ostream& print(ostream& os) const {
- return os << "I'm in the class, msg=" << msg << endl;
- }
- private:
- string msg;
- };
- ostream& operator<<(ostream& os, TestClass& obj) {
- return obj.print(os);
- }
- int main(int argc, char** argv) {
- TestClass obj;
- cout << obj;
- return 0;
- }
- class TestClass
- {
- public:
- // Have a nice friend.
- // This tightly binds this operator to the class.
- // But that is not a problem as in reality it is already tightly bound.
- friend ostream& operator<<(ostream& os, TestClass const& data)
- {
- return os << "I'm in the class, msg=" << data.msg << endl;
- }
- private:
- string msg;
- };
Advertisement
Add Comment
Please, Sign In to add comment