문제

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?

도움이 되었습니까?

해결책

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

다른 팁

In order for MFC to dynamically create your object during deserialization your class definition must provide a constructor with no parameters. Reference:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top