【问题标题】:Outputting cerr using cout使用 cout 输出 cerr
【发布时间】:2023-03-10 11:37:02
【问题描述】:

我遇到了一段代码,它基本上执行以下操作:

#include <iostream>

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

    return 0;
}

输出:

0x601088 Hi.

首先,为什么有人会做'cout

值得一提的是,上面的代码在我的机器上编译和执行没有错误。

但是,在运行相同版本的 gcc 5.4.0 的不同机器(服务器 ssh 连接)上的更复杂的代码(执行与上述相同的操作)在执行 make 时会产生此错误(为清楚起见而缩短):

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

对此有什么想法吗?

【问题讨论】:

  • Cerr 位于输出流上以获取警告。如果您重载左移运算符,则可以完成
  • 这是一个错字,很可能。有两件事发送到cout。打印出来时,第一件事不是很有意义。
  • 你不应该在 c++ 中使用 g++ 而不是 gcc 吗?
  • cout &lt;&lt; cerr &lt;&lt; " Hi."; 错了,没有意义。要么是cerr &lt;&lt; " Hi.";,要么是cout &lt;&lt; " Hi.";。从您在代码中提到的错误消息来看,作者可能打算写cerr &lt;&lt; "DB: Field " + e.table + "[" + e.index + "]." + e.field...
  • @miro_x GCC 5.4.0 默认使用标志-std=c++03 编译,这意味着它使用ISO C++03

标签: c++ compiler-errors iostream


【解决方案1】:

直到 c++11,std::basic_ios 提供了一个 implicit conversion to void*。此代码无法使用 c++11 或更高版本进行编译。你基本上有这个,它与旧版本的 gcc 一起编译:

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

    return 0;
}

【讨论】:

  • 非常感谢,太好了。我想它不再受支持,因为没有任何理由让 cout
  • @miro_x 是的,cout &lt;&lt; cerr 从一开始就是错误的,它只是碰巧编译,使用时它在实际错误消息之前输出指针的无意义值。
  • @miro_x 这样做的唯一原因是要知道流是否处于失败状态。除了检查nullptr 之外,返回指针的实际值毫无意义。如果fail() 将返回true,则转换返回nullptr,否则返回非nullptr。无论如何,只需将流转换为bool 或直接调用fail()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 2010-12-01
  • 1970-01-01
  • 2015-08-16
  • 2011-01-25
  • 2013-02-08
  • 2011-08-26
相关资源
最近更新 更多