This is related to the difference-between-cout-x-and-cout-operator-x question, but still a little different...
#include <iostream>
int main(){
std::cout << "hello" << std::endl;
std::cout.operator<<("hello2");
std::cout.operator<<(std::endl);
operator<<(std::cout, "hello3");
// operator<<(std::cout, std::endl);
return 0;
}
Q1: Why does std::cout.operator<<("hello2");
work?
From other answers on SO I would expect the compiler to complain since operator<<
is meant to be a free function and not a member of cout
. On my system, however, it prints "0x10d54df31". And, stranger yet, the following line correctly correctly executes std::endl
.
Q2: Why does operator<<(std::cout, std::endl);
not work?
I know that std::endl
is a function, but it seems strange (to me) that the hello3 output works whilst the `std::endl' doesn't. Instead the compiler throws an error:
main.cpp:10:4: error: no matching function for call to 'operator<<'
operator<<(std::cout, std::endl);
Q3: How can the first std::cout << "hello1" << std::endl;
be written in operator<<(...)
form?
If the first two questions have been answered, then this has probably already covered. It's the point of this learning exercise, so seems sensible to ask it explicitly.