What is the << operator for in C++?

后端 未结 6 1269
抹茶落季
抹茶落季 2021-01-21 13:21

I come from a C# and Java background into C++ and I\'m trying to get to understand the >> & << operators such as in

std         


        
6条回答
  •  鱼传尺愫
    2021-01-21 14:05

    << is the left-shift operator, and >> is the right-shift operator, just as they are in Java and C#.

    However, additionally, << is overloaded to provide a way of outputting values to a stream. The stream std::cout usually refers to the terminal the program was launched in, and writing something to that stream with << will write it to the terminal. >> is similarly overloaded to read from streams, and in the case of the stream std::cin to read from the terminal the program was launched on.

    This kind of thing works in C++ because you define the behaviour of operators for user-defined types. In java, operators operate only on built-in types - writing a + b is an error if a and b are instances of your own class. In C++, this is allowed if the class defines a suitable operator +.

提交回复
热议问题