2

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?

4

2 回答 2

0

You should be checking the calls to Open() for failure. You forgot to close the file after you finished writing to it. Add fileS.Close(); after you close the archive object.

if(!fileS.Open(L"C:\\source\\CMyObject.dat", CFile::modeWrite | CFile::modeCreate))
{
    std::cout << "Unable to open output file" << std::endl;
    return 1;
}
CArchive arStore(&fileS, CArchive::store);
cm.Print();
cm.Serialize(arStore);
arStore.Close();
fileS.Close();  //  <--- close the file


if(!fileL.Open(L"C:\\source\\CMyObject.dat", CFile::modeRead))
{
    std::cout << "Unable to open input file" << std::endl;
    return 1;
}
CArchive arLoad(&fileL, CArchive::load);
cm.Serialize(arLoad);
cm.Print();
arLoad.Close();
fileL.Close();  //  <--- close the file
于 2013-05-22T03:10:23.090 回答
0

为了让 MFC 在反序列化期间动态创建对象,您的类定义必须提供不带参数的构造函数。参考:

http://msdn.microsoft.com/en-us/library/47ecfxkh.aspx

于 2013-05-22T03:14:35.190 回答