簡體   English   中英

std :: ostream不能輸出一個const char數組嗎?

[英]Can't std::ostream output a const char array?

為了它的樂趣和體驗,我是 修改和 探索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行)錯誤消息:

錯誤:'operator <<'不匹配(操作數類型為'std :: ostream {aka std :: basic_ostream}'和'const char [32]')

return stream << val.name <<“(”<< val.hostname <<“:”<< val.port <<“)”;

我將代碼簡化為:

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

得到了

錯誤:'operator <<'不匹配(操作數類型為'std :: ostream {aka std :: basic_ostream}'和'const char [6]')

stream <<“你好”;

調用它的代碼如下所示:

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;
    }

毫無障礙地工作。


哦,還有一件事。

如果我包含<string> ,這有效:

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

有誰知道我錯過了什么?


PS:是錯誤pastebin。

PPS:這是請求的標頭:

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

/* includes */
#include <cstring>

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

PPS:如果你想知道為什么我沒有得到關於std::ostream未被定義的錯誤,請查看Sam的答案的第3段。

#include <iostream>可能缺失的事實是用Sherlock Holmes的方法進行調試推斷出來的:“當你消除了不可能的事情,無論剩下什么,無論多么不可能,都必須是真理”。

顯然。 std::ostream在接受const char *重載時應該沒有問題。

因此,重載決策投訴必須意味着不包括<iostream> 大多數C ++庫類都是在整個地方進行前向聲明。 包含一些隨機頭文件很可能會獲得std::ostream的前向聲明,作為免費獎勵。 所以編譯器不會抱怨這個類沒有被定義。

但除非包含<iostream> ,否則編譯器將不知道那里定義的所有重載。 而已。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM