[英]Understanding behavior of cout.operator<<()
According to the top answer to this question , cout << expr
is equivalent to cout.operator<<(expr)
. 根据这个问题的最佳答案, cout << expr
相当于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. 根据我自己的测试,当给定整数时, cout.operator<<()
与cout <<
相同。 When given a float, cout.operator<<()
coerces it to an integer. 给定一个float时, cout.operator<<()
它cout.operator<<()
转换为整数。 When given a string literal, as in cout.operator<<("hello world")
, it outputs what appears to be a memory address. 当给出字符串文字时,如cout.operator<<("hello world")
,它输出看起来cout.operator<<("hello world")
内存地址的内容。 And when given a variable holding a std::string, it gives a compiler error. 当给定一个包含std :: string的变量时,它会产生编译错误。
Could anyone give a beginner-to-intermediate-level explanation of what's going on? 任何人都可以对正在发生的事情进行初级到中级的解释吗?
It depends on expr
. 这取决于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 . 实际上,一些operator<<
s是自由 函数 ,一些是成员函数 。
Consult your favourite C++ reference to find out which. 请参阅您最喜欢的C ++参考,找出哪些。
The equivalency of cout << expr
and cout.operator<<(expr)
depends on what expr
is. cout << expr
和cout.operator<<(expr)
的等价性取决于expr
是什么。
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). 如果它是一个“内置”类型,那个cout
“知道”,那么是的,它等同于cout.operator<<(expr)
(一个成员函数)。
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&);
如果它是“用户类型”(并且std::string
count here),则它是一个重载的非成员方法,其签名类似于std::ostream& operator<<(std::ostream&, const std::string&);
etc. 等等
Why does
cout.operator<<("hello world")
print a memory address? 为什么cout.operator<<("hello world")
打印一个内存地址?
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). 上面的最好的成员方法重载(因为它被强制使用成员方法,是ostream& operator<<(const void* value);
它输出指针的值(而不是指向的内容)。
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. 相比之下, cout << "hello world"
调用非成员重载ostream& operator<<(ostream&, const char*)
,然后将每个字符插入输出中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.