std :: cout有返回值吗? [英] Does std::cout have a return value?
问题描述
我很好奇,如果std :: cout有一个返回值,因为当我这样做:
I am curious if std::cout has a return value, because when I do this:
cout << cout << "";
打印一些六进制代码。
因为 cout<< p>的操作数,所以这个打印值的含义是什么?
some hexa code is printed. What's the meaning of this printed value?
推荐答案
cout 是用户定义的类型,表达式实际上是一个函数调用。编译器必须找到与操作数匹配的最佳运算符<<
,在这种情况下,操作数都是类型 std :: ostream
。
Because the operands of cout << cout
are user-defined types, the expression is effectively a function call. The compiler must find the best operator<<
that matches the operands, which in this case are both of type std::ostream
.
有很多候选运算符重载可供选择,但我将描述最终选择的运算符重载,遵循通常的重载解决过程。
There are many candidate operator overloads from which to choose, but I'll just describe the one that ends up getting selected, following the usual overload resolution process.
std :: ostream
有一个转换操作符,允许转换为 void *
。这用于使能测试流的状态作为布尔条件(即,它允许 if(cout)
工作)。
std::ostream
has a conversion operator that allows conversion to void*
. This is used to enable testing the state of the stream as a boolean condition (i.e., it allows if (cout)
to work).
右侧的操作数表达式 cout
隐式转换为 void const * code>使用这个转换运算符,然后
运算符<<
重载,它接受一个 ostream&
void const *
被调用以写入此指针值。
The right-hand operand expression cout
is implicitly converted to void const*
using this conversion operator, then the operator<<
overload that takes an ostream&
and a void const*
is called to write this pointer value.
请注意, $ c> ostream 到 void *
转换未指定。规范只要求如果流处于坏状态,则返回空指针,否则返回非空指针。
Note that the actual value resulting from the ostream
to void*
conversion is unspecified. The specification only mandates that if the stream is in a bad state, a null pointer is returned, otherwise a non-null pointer is returned.
用于流插入的运算符<<
重载有一个返回值:它们返回作为操作数提供的流。这是允许插入操作链接(以及输入流,使用>>
的提取操作)。
The operator<<
overloads for stream insertion do have a return value: they return the stream that was provided as an operand. This is what allows chaining of insertion operations (and for input streams, extraction operations using >>
).
这篇关于std :: cout有返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!