Given a 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 a given employee e
.
Example output:
Alex Johnson
Emp#: 5719
Dept: Repair
Phone: 555-0174
I can't understand how the ostream function works. How does it get the parameter "ostream &s"?How does it overload the "<<" operator and how does the << operator work? How can it be used to write all of the information about an employee? Can someone please answer these questions in the layman's terms?
This is called overload resolution.
You've written cout << *itr
.
Compiler takes it as operator<<(cout, *itr);
, where cout
is an instance of ostream
and *itr
is an instance of employee.
You've defined function void operator<<(ostream&, employee&);
which match most closely to your call.
So the call gets translated with cout
for s
and *itr
for o
Given an employee e;
.
the following code:
cout << e;
will call your overloaded function and pass references 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 reference to the employee
should be const, since we do not change it, as pointed out by πάντα ῥεῖ
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