read/write function definiton
how would you write these functions:
bool writesomething(const Something& something);开发者_开发知识库
//or
bool writesomething(int somethingid, const Something& something);
bool readsomething(const Something& something);
//or
bool readsomething(int somethingid, Something& something);
notice that Something has a public field named id
That depends on the structure of Something. But as a general design principle, your classes should be persistence ignorant when possible.
That being said, if you want to be able to (de)serialize your objects, I would model your I/O methods on the built-in I/O streams library interfaces. Then your objects will support I/O to/from the console, files, anything else that inherits from istream
or ostream
.
In addition to maintaining a consistent interface with the standard library (and tons of third-party-code), adapting the I/O streams interface also makes it easier to write your method. If Something has an int 'id' and a string 'name' member:
ostream& operator << (ostream& os, const Something& thing)
{
os << thing.id;
os << thing.name;
return os;
}
If the members of Something are more complex you implement operator << and >> for those types, and so on down the chain.
精彩评论