C++基礎 為什麼不能cout一個string
阿新 • • 發佈:2018-11-12
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
為什麼不能cout一個string
#include<iostream>int main(int, char **){ std::string str("hello"); // 正確 std::cout << str << std::endl; // 錯誤,沒有與這些運算元(operand,std::string)相匹配的"<<"運算子 return 0;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
cout
竟然不能輸出string
std::basic_string
類的定義式,因為它們都間接地包含了<xstring>
(但不要試圖直接包含<xstring
),這就保證了你可以僅include
這些標頭檔案(如本例的#include <iostream>
)就可使用std::string
類,
typedef basic_string<char, char_traits<char>, allocator<char> > string ; // string型別其實一個類模板的特化版本的型別重定義
- 1
- 2
- 3
然而,問題在於與之相關的operator<<
卻定義在<string>
標頭檔案,你必須手動地將之包含。
所以,我們只需包含<string>
(也即對operator<<
的包含)即可實現cout
對std::string
型別的輸出:
#include <iostream>#include <string>int main(int, char**){ std::string str("hello"); std::cout << str << std::endl; return 0;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
以上的設定僅對Visual C++環境有效,也即在大多數的STL的標頭檔案中,都包含了
std::basic_string
的定義式,僅通過對這些標頭檔案的包含即可使用std::string
類,而想使用operator<<
卻需手動包含<string>
標頭檔案。在重申一遍,這些包含和依賴關係僅對Visual C++環境有效。
ostringstram 宣告與定義
同樣的問題出現在將一個string型別的輸入到一個輸出檔案流時:
#include <iostream>#include <string>int main(int, char**){ std::string str("hello world"); std::ostringstream oss; // ERROR: 不允許使用不完整的型別 oss << str; // std::cout << oss.str() << endl; return 0;}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
檢視原始碼可知:
// iosfwd -> 被間接地包含在<iostream>中typedef basic_ostringstream<char, char_traits<char>, allocator<char> > ostringstream;// xstring -> 被間接地包含在<iostream>中typedef basic_string<char, char_traits<char>, allocator<char> > string;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
僅通過對<iostream>檔案的包含,我們即可使用string
和ostringstream
等類,然而當我們想使用其成員函式時,需要包含其最終的實現版。
#include <sstream>
- 1
- 2