C++输入输出流运算符重载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38169413/article/details/88380849
  • <<的重载

    通常情况下,输出运算符的第一个形参是一个非常量ostream的引用,之所以使用引用,是因为我们无法直接复制一个ostream的对象,而ostream是非常量是因为向流写入会改变其状态。为了与标准库IO操作一致,重载 << 操作符函数应把ostream&作为其第一个参数,对类类型const对象的引用作为第二个参数,并返回对ostream形参的引用。
ostream& operator<<(ostream& out, const Sales_item& s)
{
    out << s.isbn << "\t" << s.units_sold << "\t"
        << s.revenue << “\t” << s.avg_price();
    return out;
}
  • >>的重载

    与输出操作符类似,输入操作符函数的第一个形参为流的引用,第二个形参为类类型对象的引用(非const,因为 >> 的目的就是将数据读入到该对象中)。
istream& operator>>(istream& in, Sales_item& s)
{
    double price;
    in >> s.isbn >> s.units_sold >> price;
    // check that the inputs succeeded
    if (in)
    s.revenue = s.units_sold * price;
    else
    s = Sales_item(); // input failed: reset object to default state
    return in;
}

猜你喜欢

转载自blog.csdn.net/weixin_38169413/article/details/88380849