When using cout and cin, what are the “<<” and “>>” operators doing and why do we use them?

一笑奈何 提交于 2021-02-05 07:35:21

问题


For example:

int age;
cin >> age;

cout << "You are " << age << " years old!" << endl;

Why do we use the "<<" and ">>" operators here? What are they doing? I somewhat understand bit-shifting, but I don't get how that works here.


回答1:


They are called the stream insertion operator (<<) and the stream extraction operator (>>).

These are the same operators as the left and right bit shift operators (even though they have different names). The bit shift operators are overloaded, so that when the left side is a stream, they read from or write to that stream.

They're just like any function call - it works like:

leftShift(leftShift(leftShift(leftShift(cout, "You are "), age), " years old!"), endl);

except that the function is called operator<< instead of leftShift.
Strictly speaking, there's no reason that a function called leftShift has to do a left shift, and likewise there's no reason a function called operator<< has to do a left shift.




回答2:


It's operator overloading. The bitshift operators are overloaded for the stream classes to serve a different purpose (of reading from and writing to streams). See: http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/




回答3:


>> and << have been overloaded as stream functions such as:

std::ostream & operator << (std::ostream &, int) 

(and others)

so that (in this case) when cout << 10 is used, it calls the overloaded function that will print the value.

It has nothing to do with bit shifting except that it uses the same operator '<<' and '>>'.



来源:https://stackoverflow.com/questions/37426285/when-using-cout-and-cin-what-are-the-and-operators-doing-and-why-do-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!