std::cout 有返回值吗?

2022-01-19 00:00:00 return c++ cout

我很好奇 std::cout 是否有返回值,因为当我这样做时:

I am curious if std::cout has a return value, because when I do this:

cout << cout << "";

打印了一些十六进制代码.这个打印出来的值是什么意思?

some hexa code is printed. What's the meaning of this printed value?

推荐答案

因为cout的操作数<<cout 是用户定义的类型,表达式实际上是一个函数调用.编译器必须找到与操作数匹配的最佳 operator<<,在这种情况下,它们都是 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*,然后 operator<<< 重载需要一个 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.

请注意,从 ostreamvoid* 转换产生的实际值是未指定的.规范仅要求如果流处于错误状态,则返回空指针,否则返回非空指针.

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.

用于流插入的 operator<< 重载确实有一个返回值:它们返回作为操作数提供的流.这就是允许插入操作链接的原因(对于输入流,使用 >> 的提取操作).

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 >>).

相关文章