【问题标题】:How does operator<< overloading work?operator<< 重载是如何工作的?
【发布时间】: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 &lt;&lt; e; 为给定的employee e 生成格式化输出。

示例输出:

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

我无法理解 ostream 函数的工作原理。它是如何得到参数“ostream &s”的?它是如何重载“

【问题讨论】:

  • 重载的运算符大多只是函数调用的语法糖,例如表达式cout &lt;&lt; *itr等价于operator&lt;&lt;(cout, *itr),实际上使用此语法的工作方式完全相同。
  • 你最好从书中学习这些东西。
  • 附带说明:输出运算符重载的签名应该是ostream &amp;operator&lt;&lt;(ostream &amp;s, const employee &amp;o),所有的getter函数也应该是const,因为Employee实例没有变化。

标签: c++


【解决方案1】:

这称为重载决议。 你写了cout &lt;&lt; *itr。 编译器将其视为operator&lt;&lt;(cout, *itr);,其中coutostream 的实例,*itr 是员工的实例。 您已经定义了与您的调用最匹配的函数void operator&lt;&lt;(ostream&amp;, employee&amp;);。 所以电话被翻译成cout 用于s*itr 用于o

【讨论】:

    【解决方案2】:

    给定一个employee e;。 以下代码: cout &lt;&lt; e;

    将调用您的重载函数并将引用传递给coute

    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;
    }
    

    旁注:对employee 的引用应该是const,因为我们不会改变它,正如πάντα ῥεῖ所指出的那样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-15
      • 2014-12-23
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多