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

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

    You didn't spell it out exactly, but I believe that your confusion is that you think that std::cout is a function, and you're wondering why you don't just call it like this:

    std::cout("Hello World");
    

    Well, std::cout is not a function. The function in this statement is operator<<.

    std::cout << "Hello World";
    

    Or, more specifically, the function is std::ostream::operator<<(const char*).

    The thing you need to understand is that operators are just functions with an alternative calling syntax. operator<< is overloaded as a member function of std::ostream, and std::cout is an object of std::ostream. So this:

    std::cout << "Hello World";
    

    Is an alternative way to call this:

    std::cout.operator<<("Hello World");
    

    Note that operator<< is a binary operator, which means it takes two arguments, if it's declared as a free function, and one argument if it is declared as a member function. When you use the alternative calling syntax, the object on the left is the first argument, and the object on the right is the second argument. In the case where it is declared as a member function, as it is in this case, the object on the left is the calling object, and the object on the right is the argument.

    Here's what it would look like if it were declared as a free function:

    operator<<(std::cout, "Hello World");
    

    But, whether it is declared as a member or a free function, you can still use the same alternative calling syntax.

提交回复
热议问题