This is not entirely new to C ++
C ++ does not have an automated way to store / load your objects to / from a file. In any case, you decide to go, you have to implement it yourself.
You might want to overload the << a >> statements for use with streams, or you can go with your Load and Store methods (or any names you choose as appropriate, for example Serialize / Deserialize ). I personally prefer to create my own functions rather than using operators, but that's just me.
Here is a simple example (with overloaded operators << and >> ):
#include <fstream> #include <iostream> using namespace std; class MyClass { public: MyClass (int x) : m_x(x), m_y(x+1) {} friend istream& operator >> (istream& in, MyClass& obj); friend ostream& operator << (ostream& out, const MyClass& obj); private: int m_x; int m_y; }; istream& operator >> (istream& in, MyClass& obj) { in >> obj.m_x; in >> obj.m_y; return in; } ostream& operator << (ostream& out, const MyClass& obj) { out << obj.m_x << ' '; out << obj.m_y << endl; return out; } int main(int argc, char* argv[]) { MyClass myObj(10); MyClass other(1); cout << myObj; ofstream outFile ("serialized.txt"); outFile << myObj; outFile.close(); ifstream inFile ("serialized.txt"); inFile >> other; inFile.close(); cout << other; return 0; }
It is worth mentioning that you must take care of the serialization format. In the above example, this is just text; but if you are going to store a lot of such objects, you can start thinking about serializing binary data (you will need to use the flags ofstream::binary and ifstream:binary when opening files and not need additional delimiters, for example, ' ' and endl in your serialization stream )
As a rule, when you think about serialization, you also want to think about the version of your stream - and this is another separate topic.
source share