且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

>>和<<操作符重载

更新时间:2022-06-15 06:01:34

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.