Outputting cerr using cout

◇◆丶佛笑我妖孽 提交于 2020-01-24 02:53:06

问题


I came across a piece of code that does basically the following:

#include <iostream>

using namespace std;
int main()
{
    cout << cerr << " Hi.";

    return 0;
}

Output:

0x601088 Hi.

First of all, why would anyone do 'cout << cerr' it does not make sense. Second of all, what is the meaning of the output above?

Worth to mention that on my machine the above code compiles and executes without errors.

However a much more complex code (doing the same thing as above) on a different machine (server ssh connection) running the same version of gcc 5.4.0, produces this error when doing make (shortened for clarity):

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::ostream {aka std::basic_ostream<char>}’)
     cout << cerr << "DB: Field " + e.table + "[" + e.index + "]." + e.field

Any thoughts on this?


回答1:


Until c++11, std::basic_ios offered an implicit conversion to void*. This code won't compile with c++11 or later. You basically have this, which compiles with older versions of gcc :

#include <iostream>
int main()
{
    void * x = std::cerr;
    std::cout << x << " Hi.";

    return 0;
}


来源:https://stackoverflow.com/questions/47835651/outputting-cerr-using-cout

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