简体   繁体   中英

Understanding behavior of cout.operator<<()

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

According to responses to this question , the statement above is untrue.

According to my own testing, cout.operator<<() is the same as cout << when given an integer. When given a float, cout.operator<<() coerces it to an integer. When given a string literal, as in cout.operator<<("hello world") , it outputs what appears to be a memory address. And when given a variable holding a std::string, it gives a compiler error.

Could anyone give a beginner-to-intermediate-level explanation of what's going on?

It depends on expr .

The answers to both questions are speaking to that specific case, not a blanket guarantee.

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

Consult your favourite C++ reference to find out which.

The equivalency of cout << expr and cout.operator<<(expr) depends on what expr is.

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

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

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

The best member method overload to the above (since it is being forced to use the member method, is ostream& operator<<(const void* value); which outputs the value of the pointer (not what is being pointed to).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM