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

后端 未结 6 1341
抹茶落季
抹茶落季 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:28

    In general the << and >> operators have the same meaning. However, in the cases that you have given they are stream write and read operators respectively. Specifically, << is the write operator (think of it as pointing towards the stream) and >> is the read operator (pointing away from the stream).

    They are handled by overloading the << and >> operators. In particular, the C++ paradigm is to add overloads for << and >> for ostreams and istreams respectively to handle input and output. C++ does not have a built-in paradigm of ToString() the way Java and C# do.

    Finally, std::cout, std::cin and std::cerr are instances of ostream, istream and ostream respectively, which is why they get the << and >> overloads.

    For instance, the following code outputs Hello World to the standard output stream.

    std::cout << "Hello World" << std::endl;
    

    Finally, std::endl is a special ostream that adds a newline and flush the stream.

提交回复
热议问题