重载输入运算符
我有一个输入运算符的函数原型,但我不确定它们是什么以及它们的含义,我认为 istream 是类型为 Stream 的对象,而 sourceFileStream 是通过引用传递的。有人可以解释一下每个参数的含义吗?
istream& operator >>(istream &sourceFileStream, Chart &aChart)
I have a function prototype for an input operator but I'm not sure what they all are and what they mean, I think istream is an object of type stream &sourceFileStream is being passed by reference. Can someone explain what each of the parameters mean ?
istream& operator >>(istream &sourceFileStream, Chart &aChart)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
istream 是一个输入流: http://www.cplusplus.com/reference/iostream/istream/
sourceFileStream
和aChart
都是通过引用传入的。istream is an input stream: http://www.cplusplus.com/reference/iostream/istream/
Both
sourceFileStream
andaChart
are being passed in by reference.istream&
是返回类型,函数完成后通过引用返回sourceFileStream
参数。这样做是为了让您可以链接运算符(在同一语句中多次使用它们)。
我敢打赌,您会更熟悉链接输出运算符...因此,例如,您可以使用 <<运算符在这一行中多次出现:
因为它返回一个引用,所以它正在操作的流(cerr)。
istream& sourceFileStream 作为参数是一个输入流(读取文件或类似的东西)。它是通过引用传递的,因此您要修改传入的流,然后出于上述原因返回它(很可能是通过在读取中向前读取并移动其内部指针来修改它)。
您还通过引用传递图表对象,最有可能从流内容填充其内部数据成员。因此,在使用此运算符结束时,您的图表的成员将从流内容中填充,如您在此函数的定义中指定的那样。 PS:通过引用意味着传入此函数的对象将被直接修改,因为 aChart 将是该对象的别名。如果不是通过引用,则该对象的副本将被修改,并且该函数将毫无用处。
istream&
is the return type, it returns thesourceFileStream
parameter by reference after the function completes.This is done so you can chain the operators (use them multiple times in the same statement).
You'd be more familiar with chaining output operators I'd bet... so, for example, you can use the << operator many times in this line:
because it returns a reference so the stream (cerr) that it is manipulating.
istream& sourceFileStream
as a parameter is an input stream (reading a file or something like that). It's passed by reference, so you're modifying the stream that gets passed in and then returning it for the reason stated above (most likely modifying it by reading forward in the reading and moving its internal pointers).You're passing a chart object by reference as well, most likely to populate its internal data members from the stream contents. So, at the end of the use of this operator, your Chart's members will be populated from the stream contents as you specify in this function's definition. PS: by reference means that the object passed into this function will be modified directly as aChart will be an alias for that object. If it wasn't by reference, a copy of that object would be modified and this function would be useless.