[英]How does operator<< overloading work?
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
.为给定的
employee e
生成格式化输出。
Example output:示例输出:
Alex Johnson
Emp#: 5719
Dept: Repair
Phone: 555-0174
I can't understand how the ostream function works.我无法理解 ostream 函数是如何工作的。 How does it get the parameter "ostream &s"?How does it overload the "<<" operator and how does the << operator work?
它如何获得参数“ostream &s”?它如何重载“<<”运算符以及<<运算符如何工作? 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
.你已经写了
cout << *itr
。 Compiler takes it as operator<<(cout, *itr);
编译器把它当作
operator<<(cout, *itr);
, where cout
is an instance of ostream
and *itr
is an instance of employee. ,其中
cout
是ostream
的实例, *itr
是员工的实例。 You've defined function void operator<<(ostream&, employee&);
您已经定义了函数
void operator<<(ostream&, employee&);
which match most closely to your call.与您的通话最匹配。 So the call gets translated with
cout
for s
and *itr
for o
所以调用被转换为
cout
为s
和*itr
为o
Given an employee e;
给定一个
employee e;
. . the following code:
cout << e;
以下代码:
cout << e;
will call your overloaded function and pass references to cout
and e
.将调用您的重载函数并将引用传递给
cout
和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 πάντα ῥεῖ旁注:如 πάντα ῥεῖ 所指出的,对
employee
的引用应该是常量,因为我们不会更改它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.