Overloading the operator << to display the elements of an object without using a friend function

I am updating cpp after a long space, trying to understand operator overload methods. I tried to overload operator <to output the elements of the object. But I cannot do this without using a friend function. I am looking for a method without using a friend function.

here is my def class:

 class Add{ private: int x; public: friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1 void operator<<(ostream& ostr); //Method 2 }; 

implementation of functions

 //Method 1 ostream& operator<<(ostream &ostr, Add const& rhs) { ostr<<rhs.x; return ostr; } //Method 2 void Add::operator<<(ostream& ostr) { cout<<" using operator<< \n"; ostr<<x; } 

calls the main function

 cout<<Obj_Add; //calls the Method 1 Obj_Add<<cout; //calls the Method 2 

Now my question is: I would like to receive type 1 calls to the method without using the friend function. But I don’t know if this is possible or not in cpp. I tried several implementation options, but they all give me compilation errors. Please help me understand that I am not here.

+4
source share
4 answers

If you have public access functions in your class or stream , you don't need friendship with operator<< :

 // v1 class foo{ public: int data() const{ return _data; } private: int _data; }; std::ostream& operator<<(std::ostream& o, foo const& f){ return o << f.data(); } // v2 class foo{ public: void stream_to(std::ostream& o){ o << _data; } private: int _data; }; std::ostream& operator<<(std::ostream& o, foo const& f){ f.stream_to(o); return o; } 

v2 has the added benefit of allowing stream_to be a virtual function that is useful for polymorphic base classes, so you don't need to redefine operator<< for each derived class, just stream_to .

+5
source

This is possible using the getter x.

if the <operator is not a friend, it cannot access member x

 class Add { private: int x; public: int getX() { return x; } }; //Method 1 ostream& operator<<(ostream &ostr, Add const& rhs) { //ostr<<rhs.x; //Fail: x is private ostr << rhs.getX(); //Good return ostr; } 
+2
source

You can avoid using the operator function as a friend if you have other ways to get x from the object.

 class Foo { private: int bar; public: int get_bar() const { return bar; } }; ostream &operator<<(ostream &os, const Foo &foo) { os << foo.get_bar(); return os; } 
+1
source

This is not possible if you have not added any mechanism to get x out, for example. a public

 // in the class int get_x() const { return x; } 

or other mechanism for printing an object

 // outside the class std::ostream &operator<<(std::ostream &out, Add const &obj) { obj.print(out); return out; } 
0
source

Source: https://habr.com/ru/post/1390420/


All Articles