【问题标题】:Can't std::ostream output a const char array?std::ostream 不能输出 const char 数组吗?
【发布时间】:2017-01-06 04:15:42
【问题描述】:

为了获得它的乐趣和体验,我正在修改和探索Blobby Volley 2 1.0 (Linux) 的源代码。

嗯...我修改源代码,但我什至无法编译程序。 (伤心,不是吗?)

这是导致错误的代码:

std::ostream& operator<<(std::ostream& stream, const ServerInfo& val) {
    return stream << val.name << " (" << val.hostname << ":" << val.port << ")";
    }

尝试用 g++ 5.4.0 编译它会给出以下(简化的输出——原始输出约为 443 行)错误消息:

error: no match for ‘operator

返回流

我将代码简化为:

std::ostream& operator<<(std::ostream& stream, const ServerInfo& val) {
    stream << "hello"; //can't get simpler than this, right?
    return stream;
    }

得到了

错误:'operator

调用它的代码如下:

std::cout << "duplicate server entry\n";
std::cout << info << "\n"; //it's called here

最令我惊讶的是,我们都知道std::cout 及其同类可以处理char 数组。

例如,

#include <iostream>
#include <string>

int main () {
    const char a[6] = "hello";
    std::cout << a << std::endl; //No problem here!
    return 0;
    }

工作顺利。


哦,还有一件事。

如果我包含&lt;string&gt;,这可行:

std::ostream& operator<<(std::ostream& stream, const ServerInfo& val) {
    stream << std::string("hello");
    return stream;
    }

有人知道我错过了什么吗?


PS:这是pastebin of the errors.

PPS:以下是请求的标头:

/* header include */
#include "NetworkMessage.h"

/* includes */
#include <cstring>

#include "UserConfig.h"
#include "SpeedController.h"

PPS:如果您想知道为什么我没有收到关于未定义 std::ostream 的错误,请查看 Sam 答案的第 3 段。

【问题讨论】:

  • 您报告了一个通常不应该发生的错误,所以我怀疑可能还有其他问题。所以……是的! :-)
  • 最可能的答案是有问题的翻译单元缺少 的包含。
  • 如果你没有#include &lt;iostream&gt;,肯定看起来像你得到的错误——它知道的唯一重载是你写的自定义的。
  • @JefréN。从长远来看,现在删除这个问题可能会节省审稿人的工作,因为我怀疑这就是这个问题的最终命运。但这取决于你。不过很高兴你想通了。
  • @JasonC:如果不是因为最初猜出问题所在的 Sam Varshavchik 给出了我要求的答案,我会删除这个问题。但事实上,我想我会让 stackoverflow 顺其自然……:D

标签: c++ operator-overloading ostream


【解决方案1】:

#include &lt;iostream&gt; 可能丢失的事实是使用福尔摩斯调试方法推断出来的:“当你消除了不可能的事情时,剩下的无论多么不可能,都必须是事实”。

很明显。 std::ostream 接受 const char * 重载应该没有问题。

因此,过载解决投诉必须意味着 &lt;iostream&gt; 不包括在内。大多数 C++ 库类都是前向声明的。包含一些随机的头文件可能会让你得到std::ostream 的前向声明,作为免费奖励。所以编译器不会抱怨这个类没有被定义。

但除非包含&lt;iostream&gt;,否则编译器不会知道那里定义的所有重载。就是这样。

【讨论】:

  • #include &lt;ostream&gt;(声明 const char* 重载 - 27.7.3.1)就足够了,而不是 iostream(包括 ostream - 27.4.1)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2021-03-21
  • 2016-05-08
相关资源
最近更新 更多