How does the << overload operator work?

Given the class:

 struct employee { string name; string ID; string phone; string department; }; 

How does the following function work?

 ostream &operator<<(ostream &s, employee &o) { s << o.name << endl; s << "Emp#: " << o.ID << endl; s << "Dept: " << o.department << endl; s << "Phone: " << o.phone << endl; return s; } 

cout << e; produces formatted output for the given employee e .

Output Example:

 Alex Johnson Emp#: 5719 Dept: Repair Phone: 555-0174 

I cannot understand how the ostream function works. How does it get the parameter "ostream & s"? How does it overload "<<the operator and how <the operator’s work? How can it be used to write all the information about the employee? Can someone answer these questions in the conditions of a layman?

+5
source share
2 answers

This is called overload resolution. You wrote cout << *itr . The compiler takes it as operator<<(cout, *itr); where cout is an instance if ostream and *itr is an employee instance. You have defined the function void operator<<(ostream&, employee&); that most closely matches your challenge. So he performed the cout transfer for s and *itr for o

+8
source

Given employee e; . following code: cout << e;

will call your overloaded function and pass links to cout and e .

 ostream &operator<<(ostream &s, const employee &o) { // print the name of the employee e to cout // (for our example parameters) s << o.name << endl; // ... // return the stream itself, so multiple << can be chained return s; } 

Sidenote: the employee reference must be const, since we don’t change it, as indicated by πάντα ῥεῖ

+1
source

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


All Articles