【发布时间】:2015-10-30 07:37:19
【问题描述】:
给定一个类:
struct employee {
string name;
string ID;
string phone;
string department;
};
下面的函数是如何工作的?
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; 为给定的employee e 生成格式化输出。
示例输出:
Alex Johnson
Emp#: 5719
Dept: Repair
Phone: 555-0174
我无法理解 ostream 函数的工作原理。它是如何得到参数“ostream &s”的?它是如何重载“
【问题讨论】:
-
重载的运算符大多只是函数调用的语法糖,例如表达式
cout << *itr等价于operator<<(cout, *itr),实际上使用此语法的工作方式完全相同。 -
你最好从书中学习这些东西。
-
附带说明:输出运算符重载的签名应该是
ostream &operator<<(ostream &s, const employee &o),所有的getter函数也应该是const,因为Employee实例没有变化。
标签: c++