>>和<<操作符重载 [英] >> and << operator overloading

查看:171
本文介绍了>>和<<操作符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚为我的编程课做了一个测验,并得到了这个问题:

I just did a quiz for my programming class and got this question wrong:


函数的返回类型为
重载操作符< 必须是对ostream对象的
引用。

The return type of the function to overload the operator << must be a reference to an ostream object.

这对我来说似乎不对。当然C ++有点比这更开放。但我想我会问这里。这是正确的(或错误)?我的C ++知识开始真正褪色,当涉及到操作符重载..

This does not seem right at all to me. Surely C++ is a bit more open ended than this. But I thought I'd ask here anyway. How is this right (or wrong)? My C++ knowledge begins to really fade when it comes to operator overloading..

推荐答案

C ++不要求返回类型是对 ostream 对象的引用。但是,如果您尝试执行以下操作:

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:

cout << instance_of_custom_type << 3 << "hi" << endl;

然后您将需要:

ostream &operator << (ostream &os, custom_type &t);

然而,如果你正在做类似于编写大型整数类型,它可能是这样的:

However, if you were doing something like writing a large integer type, and wanted to support bit shifting, it might be something like:

BigInt operator << (const BigInt &i, unsigned int shift);






要进一步扩展, << 运算符用于位移。 1<< 8 为256。 C ++为此添加了一个(稍微混乱的)第二次使用,并在 ostream 上重载它以表示输出到流。你可以在一个重载的操作符里面做任何你喜欢的事情 - 它的作用就像一个函数,然而,操作符有一个人类的期望与他们附加:程序员期望,在C + +,< 是位移位或流输出。


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 on ostream 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.

这篇关于&gt;&gt;和&lt;&lt;操作符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆