簡體   English   中英

fstream和ofstream operator <<差異

[英]fstream and ofstream operator << difference

我想重載operator <<以將對象序列化為文件(追加)。 我應該使用哪個流? ofstreamfstream 有什么區別?

std::ofstream& operator<<(std::ofstream& ofs, const MyData&);
std::fstream& operator<<(std::fstream& fs, const MyData&)

謝謝傑克

你應該為ostream重載操作符,然后你可以自然地使用它來源於任何類的實例 - ofstream,fstream(繼承自iostream,繼承自istream和ostream),ostringstream和stringstream(也繼承iostream) )

std::ostream& operator<<(std::ostream& os, const MyData&);

重載std::ostream會更有意義。 如果可以更一般地將實現限制為特殊類型的輸出流,為什么? 您還可以將序列化打印到std::cout ,這簡化了調試。

這里給出了關於iostream關系和繼承用法的一個很好的概述。 此外,每個特定流的概述頁面都顯示了繼承關系。

AFAIK, ofstream("file.txt")fstream("file.txt", ios::out)

如果您還想從同一文件中讀取,請使用fstream 如果僅附加,則使用ofstream 在任何一種情況下,如果您不想覆蓋現有數據,請在打開時使用ios::app標志。

暫無
暫無

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

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