>>>和<<运算符重载
我刚刚为我的编程课做了一个测验,并答错了这个问题:
函数的返回类型 重载运算符
<<
必须是 对 ostream 对象的引用。
这对我来说似乎根本不对。当然,C++ 比这更开放。但我想我还是会在这里问。这如何是对的(或错的)?当涉及到运算符重载时,我的 C++ 知识开始真正消失。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C++ 不要求返回类型是对 ostream 对象的引用。但是,如果您尝试执行以下操作:
那么您将需要:
但是,如果您正在执行诸如编写大整数类型之类的操作,并且想要支持位移位,则可能会类似于:
为了进一步扩展这一点,
<<
运算符最初的用途是进行位移位。 <代码>1 <<例如,8 是 256。 C++ 为此添加了第二个用途(有点令人困惑),并在 ostream 上重载它以表示“输出”到流。您可以在重载运算符中做任何您喜欢的事情 - 它的工作方式就像函数一样,但是,运算符具有人类的期望:在 C++ 中,程序员期望<<
是位移位或流输出。It is not required by C++ that the return type be a reference to an
ostream
object. However, if you are trying to do something like:Then you will need:
However, if you were doing something like writing a large integer type, and wanted to support bit shifting, it might be something like:
To expand this a bit further, the original use of the
<<
operator is for bit shifting.1 << 8
is 256, for example. C++ added a (slightly confusing) second use for this, and overloaded it onostream
to mean "output" to the stream. You can do whatever you like within an overloaded operator - it works just like a function, however, operators have a human expectation attached with them: programmers expect, in C++, that<<
is bit shifting or stream output.将返回类型作为对作为引用参数传递给重载插入运算符的同一流对象的引用,使我们能够编写如下代码
Having the return type as a refernce to the same stream object passed as reference argument to the overloaded insertion operator enables us to write code such as
说“必须”是不正确的,可能“通常”才是正确的词,为什么?因为正如大多数答案已经指出的那样,它在使用 iostreams 时提供了对象链接的便利。
To say 'must' is incorrect, probably 'usually' is the correct word, and why? Because as most of the answers have already pointed out, it gives the convenience of
object chaining
, while working withiostreams
.从更一般的角度来看,
operator<<
应始终返回其左侧操作数,以便链式调用,就像operator=
一样。在处理
库时,这恰好是对std::ostream
的引用。From the more general point of view,
operator<<
should always return it's left hand side operand in order to chain calls, just likeoperator=
.When dealing with the
<iostreams>
library, this happens to be a reference tostd::ostream
.让它返回 ostream 引用的目的是为了让您可以将它们链接在一起。否则你必须写
cout << 1;计算<< “是一个数字”;计算<<结束
The purpose of having it return the ostream reference is so that you can chain them together. Otherwise you'd have to write
cout << 1; cout << " is a number"; cout << endl
这是不对的。它只有在 iostreams 的上下文中才是正确的,在我看来,iostreams 可能是无关紧要且无趣的,它永远不应该以这种形式被放出笼子。如果您的代码中不包含 iostreams,您可以做您喜欢的事情。但我不会重载这些运算符来执行除移位类之外的任何操作,无论这意味着通过整数值,或者通过可以以某种方式简化为整数值的类。
It isn't right. It's only correct in the context of iostreams, which in my probably irrelevant and uninteresting opinion should never have been let out of the cage in that form. If you don't include iostreams in your code you can do what you like. But I wouldn't be overloading these operators to do anything except shift classes, whatever that means, by integer values, or maybe by classes that can be reduced to integer values somehow.