本文介绍了为什么我们需要在重载>>时返回对istream/ostream的引用.和<<操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不返回dindout会发生什么,实际上我正在读一本书,其中作家返回了流引用

What happens if I do not return din or dout, actually I'm reading a book in which writer returns back stream references

istream & operator>>(istream &din,vector &a)
{
    for(int i=0;i<size;i++)
    din>>a.v[i];
    return din;
}

ostream & operator<<(ostream &dout,vector &a)
{
    dout<<"("<<a.v[0];
    for(int i=1;i<size;i++)
    dout<<", "<<a.v[i];
    dout<<")";
    return dout;
}

推荐答案

原因是多个事实的组合.

The reason is a combination of several facts.

  1. 您希望能够像在

  1. You want to be able to chain input and output operations as in

in  >> x >> y;

out << z << std::precision(10) << t << std::endl;

,因此您必须返回允许再次使用operator<<的内容.

so you must return something that allows operator<< again.

由于您希望操作员对任何istream(即,从std::istream派生的任何对象)进行操作,因此无法定义

Since you want your operator to work on any istream, i.e. any object derived from std::istream, you cannot define

operator<<(istream_type, object);    // take istream by value

因为这仅适用于特定的istream类型istream_type,但不适用于通用的istream.为此,必须使用多态性,即采用引用或指针(将是从std::istream派生的类的引用或指针).

since this would only work for the specific istream type istream_type, but not for a generic istream. For that one must use polymorphism, i.e. either take a reference or a pointer (which will be a reference or pointer to a class derived from std::istream).

由于您仅具有对istream的引用,因此无法返回istream对象本身(其类型可能甚至在operator<<的定义时都未定义),而是仅返回您的引用.我有.

Since you only have a reference to the istream, you cannot return the istream object itself (which may be of a type not even defined at the point of the definition of operator<<) but only the reference you've got.

可以通过定义operator<<template并按值获取并返回istream_type来克服此限制,但这需要istream类型具有复制构造函数,而对于它而言,它可能没有有充分的理由.

One could get around this restriction by defining operator<< a template and take and return the istream_type by value, but that requires the istream type to have a copy constructor, which it may well not have for good reasons.

为了引起多态性,原则上可以使用指针(指向流)而不是引用.但是,operator<<(stream*,const char*)是在C ++中是不允许的(至少一个操作数必须是类或枚举类型).

In order to envoke polymorphism one could, in principle, use pointers (to streams) rather than references. However, operator<<(stream*,const char*) is not allowed in C++ (at least one operand must be of class or enumeration type).

因此,使用流指针时,必须使用函数调用语法,然后返回C风格的fprintf(stream*, args...).

Thus, with stream pointers one must use function-call syntax and you're back with C-style fprintf(stream*, args...).

此外,指针可以为null或悬空,实际上是指针的默认状态(在没有初始化程序的情况下声明),而引用可以被认为是有效的(在没有初始化程序的情况下不能声明).

Moreover, pointers can be null or dangling, which in fact is their default state (when declared without initializer), while a reference can be assumed to be valid (it cannot be declared without initializer).

这篇关于为什么我们需要在重载&gt;&gt;时返回对istream/ostream的引用.和&lt;&lt;操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 08:05