gpt4 book ai didi

c++ - operator<< 重载如何工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:10 25 4
gpt4 key购买 nike

给定一个类:

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); , 其中coutostream 的实例和 *itr是雇员的实例。您已经定义了函数 void operator<<(ostream&, employee&);最接近您的电话。所以电话被翻译成cout对于 s*itr对于 o

关于c++ - operator<< 重载如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33430867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com