What's the difference between cout<<cout and cout<<&cout in c++?

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

This might be a beginner question and understanding how cout works is probably key here. If somebody could link to a good explanation, it would be great. cout and cout print hex values separated by 4 on a linux x86 machine.

回答1:

cout is equivalent to cout . This is the idiom used before C++11 to determine if an iostream is in a failure state, and is implemented in std::ios_base; it usually returns the address of static_cast<:ios_base>(&cout).

cout prints out the address of cout.

Since std::ios_base is a virtual base class of cout, it may not necessarily be contiguous with cout. That is why it prints a different address.



回答2:

cout is using the built-in conversion to void* that exists for boolean test purposes. For some uninteresting reason your implementation uses an address that is 4 bytes into the std::cout object. In C++11 this conversion was removed, and this should not compile.

cout is printing the address of the std::cout object.



回答3:

cout is passing cout the address of cout.

cout is printing the value of implicitly casting cout to a void* pointer using its operator void*.



回答4:

As already stated, cout uses the void* conversion provided for bool testing (while (some_stream){ ... }, etc.)

It prints the value &cout + 4 because the conversion is done in the base implementation, and casts to its own type, this is from libstdc++:

operator void*() const { return this->fail() ? 0 : const_cast(this); } 


回答5:

cout is passing the address of cout to the stream.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!