Understanding the behavior of cout.operator << ()

According to the top answer to this question , cout << expr equivalent to cout.operator<<(expr) .

According to the answers to this question , the above statement is incorrect.

According to my own testing, cout.operator<<() matches cout << when specifying an integer. When float is given, cout.operator<<() forces its integer. When a string literal is given, as in cout.operator<<("hello world") , it outputs what seems like a memory address. And when a variable containing std :: string is given, it gives a compiler error.

Can someone explain the initial and intermediate explanation of what is happening?

+5
source share
2 answers

It depends on expr .

The answers to both questions relate to this particular case, and not a full guarantee.

In fact, some of the operator<< functions are free , and some of them are member functions .

Consult your favorite C ++ link to find out which one.

+5
source

The equivalence of cout << expr and cout.operator<<(expr) depends on the fact that expr .

If it lands as a "built-in" type that cout "knows", then yes, it is equivalent to cout.operator<<(expr) (member function).

If this is a "user type" (and here std::string ), then this is an overloaded non-member method with signatures similar to std::ostream& operator<<(std::ostream&, const std::string&); etc.

Why cout.operator<<("hello world") print a memory address?

The best member method is overloaded to the above (since it is forced to use a member method, this is ostream& operator<<(const void* value); which displays the value of the pointer (and not what it points to).

In contrast, cout << "hello world" causes a non-member overload of ostream& operator<<(ostream&, const char*) , and this in turn inserts each character into the output file.

+3
source

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


All Articles