首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

为啥第二次打开文件时,文档类的Serialize函数没被调用

2013-07-04 
为什么第二次打开文件时,文档类的Serialize函数没被调用?为什么第二次打开文件时,文档类的Serialize函数没

为什么第二次打开文件时,文档类的Serialize函数没被调用?
为什么第二次打开文件时,文档类的Serialize函数没被调用?

情况是这样的:
我在文档里里面写了

if (ar.IsStoring())
{
  CString s(_T("This is a test"));
  ar<<s;
}
else
{
  CString s;
  ar>>s;
  Messagebox(AfxGetApp()->m_pMainWnd->h_hWnd, s, _T("测试"), MB_ICONWARNING);
}

然后在工具栏里选择保存文件。然后打开这个保存的文件,出Messagebox,点确定后,再在工具栏打开这个文件,就不出这个Messagebox了,这是为什么呢?
[解决办法]
看下你的调用栈第一次和第二次有什么不同的,CArchive相关知识:
Storing and loading CObjects via an archive requires extra consideration. In certain cases, you should call the Serialize function of the object, where the CArchive object is a parameter of the Serialize call, as opposed to using the << or >> operator of the CArchive. The important fact to keep in mind is that the CArchive >> operator constructs the CObject in memory based on CRuntimeClass information previously written to the file by the storing archive.
Therefore, whether you use the CArchive << and >> operators, versus calling Serialize, depends on whether you need the loading archive to dynamically reconstruct the object based on previously stored CRuntimeClass information. Use the Serialize function in the following cases:
When deserializing the object, you know the exact class of the object beforehand.
When deserializing the object, you already have memory allocated for it.
Caution
If you load the object using the Serialize function, you must also store the object using the Serialize function. Don't store using the CArchive << operator and then load using the Serialize function, or store using the Serialize function and then load using CArchive >> operator.
In summary, if your serializable class defines an embedded CObject as a member, you should not use the CArchive << and >> operators for that object, but should call the Serialize function instead. Also, if your serializable class defines a pointer to a CObject (or an object derived from CObject) as a member, but constructs this other object in its own constructor, you should also call Serialize.
------解决方案--------------------


函数Serialize()的调用
当读取文件或保存文件时,都要发生文档对象的序列化操作,即调用函数Serialize().
(1)读取操作
<1>单击应用程序菜单“File
[解决办法]
New”,应用程序调用函数OnNewDocument()建立新文档。OnNewDocument()调用虚函数DeleteContents()清空文档类数据成员,然后再调用SetModifiedFlag(FALSE)将文档修改标志清除。
<2>单击应用程序菜单"File
[解决办法]
Open",应用程序调用函数OnOpenDocument()打开已有文档。函数OnOpenDocument()调用GetFile()获取给定文件的CFile指针,再调用DeleteContents()函数清空文档类数据成员,然后把CFile指针构造CArchive对象交给Serialize函数完成读文件重建文档对象的工作,再调用SetModifiedFlag(FALSE)将文档修改标志清除。

http://masust.blog.163.com/blog/static/1469540842011525102955787/

难道是VC的优化?发现是同一个文档,且已经完成读取文件。

热点排行