I want to overload operator<< to serialize an object to a file (append). Which stream should I use? ofstream
or fstream
? what is the difference?
std::ofstream& operator<<(std::ofstream& ofs, 开发者_高级运维const MyData&);
std::fstream& operator<<(std::fstream& fs, const MyData&)
Thanks Jack
You should overload the operator for ostream, then you can use it naturally for an instance of any class which derives from that - ofstream, fstream (inherits from iostream, which inherits from both istream and ostream), ostringstream and stringstream (inherits iostream, too)
std::ostream& operator<<(std::ostream& os, const MyData&);
It would make more sense to overload for std::ostream
. Why should your implementation be restricted to a special type of output stream if it can be more general? You also get the benfit of printing your serialization to std::cout
which simplyfies debugging.
A good overview about the relations of iostreams and the usage of inheritance is given here. Also every overview page to a specific streams shows the inheritance relations.
AFAIK, ofstream("file.txt")
is the same as fstream("file.txt", ios::out)
.
If you also want to read from the same file, use fstream
. If append-only, use ofstream
. In either case, if you don't want to overwrite existing data, use the ios::app
flag when opening.
精彩评论