开发者

C++ << >> operators

I can use for example the << operator to type my name as follows:

std::cout<<"My name is: "<<name<<std::endl;

On Wikipedia it mentions the following regarding << and >>:

In the context of iostreams, writers often will refer to ​<< ​ and ​>>​ as the “put-to” or "stream insertion" and “get-from” or "stream extraction" operators, respectively.

In the example code above, isn't t开发者_C百科he << performing concatenation? Does concatenation have a special operator in C++?

Thanks.


Nothing has got a special operator in C++. std::ios (its derived) misused operator>> and operator<< in order to provide a simple way to perform stream operation: those two operators have otherwise got a different semantics in C++.

An operator used to concatenate two std::string is operator+ (but I think in this case they didn't misuse it: operator+ between two strings is doing what I'd be expecting).


In this case concatenation isn't actually occurring. Instead, each of the strings are being written, in turn, to the output stream. In this case, that stream happens to be standard out.


If you are concatenating, you would use operator +. But as @tsellon says, your example is not, technically speaking, concatenation - it is writing sequentially into a stream. Maybe the difference seems abstract but the implications are very real.


In the context of iostreams, operator << inserts data into the stream. What the stream does with it is an entirely different story. It may concatenate strings (as is the case for std::stringstream), but it may also do something completely different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜