我使用Visual Studio2010学习Visual C++。我尝试使用MFC CObject的序列化函数。我不能用序列化函数加载我的对象我的代码:
#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();
}程序在字符串上终止:
cm.Serialize(arLoad);你能告诉我这段代码出了什么问题吗?
发布于 2013-05-22 11:10:23
您应该检查对Open()的调用是否失败。在完成写入后,您忘记关闭该文件。关闭存档对象后添加fileS.Close();。
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-22 11:14:35
为了让MFC在反序列化期间动态创建对象,您的类定义必须提供不带参数的构造函数。参考资料:
http://msdn.microsoft.com/en-us/library/47ecfxkh.aspx
https://stackoverflow.com/questions/16682804
复制相似问题