[英]std::ostream not formatting const char* correctly the first time it's used
[英]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;
}
有誰知道我錯過了什么?
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.