I learn Visual C++ with Visual Studio 2010. I tried to use Serialize function of MFC CObject. I can't load my object with Serialize function My code:
#include <afxwin.h>
#include <iostream>
using std::cout;
using std::endl;
// CMyObject
class CMyObject : public CObject
{
public:
int x, y;
CMyObject(int _x=0, int _y=0) : CObject(), x(_x), y(_y) {}
void Serialize(CArchive &ar);
void Print() const;
DECLARE_SERIAL(CMyObject)
};
IMPLEMENT_SERIAL(CMyObject, CObject, 1)
void CMyObject::Serialize(CArchive &ar)
{
CObject::Serialize(ar);
if (ar.IsStoring())
ar << x;
else
ar >> x;
}
void CMyObject::Print() const
{
cout << "CMyObject (" << x << "," << y << ")" << endl;
}
int main()
{
CMyObject cm(1,3);
CFile fileS, fileL;
fileS.Open(L"C:\\CMyObject.dat", CFile::modeWrite | CFile::modeCreate);
CArchive arStore(&fileS, CArchive::store);
cm.Print();
cm.Serialize(arStore);
arStore.Close();
cm.x = 2;
cm.Print();
fileL.Open(L"C:\\CMyObject.dat", CFile::modeRead);
CArchive arLoad(&fileL, CArchive::load);
cm.Serialize(arLoad);
cm.Print();
arLoad.Close();
}
Program died on the string:
cm.Serialize(arLoad);
Could you tell me what's wrong with this code?