Difference between `cout << x` and` cout.operator << (x) `?

I am trying to use for_each to print a line vector in cout. However, when formulating the operator, I found that std::ostream::operator<<(const std::string &); not defined, leading to compiler errors. The following code illustrates the problem:

 #include <iostream> #include <string> int main() { std::string message = "Hello World!\n"; // This works std::cout << message; // Compiler error std::cout.operator <<(message); } 

I thought that both statements should look identical to the compiler. This is apparently not the case. So what is the difference?

solvable

As Tomalak and Prasun said, I needed to call this function:

 std::ostream& operator<<(std::ostream&, const std::string&); 

So the following sample will work:

 #include <iostream> #include <string> int main() { std::string message = "Hello World!\n"; operator<<(std::cout, message); } 

Regarding my original purpose (using for_each to print a line vector): It seems that it is better to use std::copy with std::ostream_iterator , as shown here: How do I use for_each to output to cout?

+2
source share
2 answers

You are looking for std::ostream& operator<<(std::ostream&, const std::string&); . This is a free feature.

+13
source

std::cout << message; will be equivalent to operator << (std::cout, message) not what you wrote.

the << operator was defined as a free function, not as a member function

std::ostream& operator<<(std::ostream& out, const std::string& s) { ... }

+13
source

Source: https://habr.com/ru/post/1268634/


All Articles