且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MFC CArchive销毁对象

更新时间:2022-06-24 14:56:30

在第一个函数中,归档对象ar在函数中实例化,因此仅当它超出范围时(即,当您退出函数时)才会被销毁.如您所见,您无法将同一对象重新声明为不同于其第一个声明的对象.如果您想重用它,则可以使ar成为以下指针:CArchive* ar,并使用newdelete对其进行管理.
In your first function your archive object ar is instantiated within the function, so it will only be destroyed when it goes out of scope, i.e. when you exit the function. As you have seem you cannot redeclare the same object to be something different from its first declaration. If you wish to reuse it then make ar a pointer thus: CArchive* ar, and use new and delete to manage it.


2buck56写道:
2buck56 wrote:

理查德,谢谢你的建议.但是,我尝试将CArchive * ar与new和delete一起使用.即使删除了ar指针,也无法重新使用它.编译器抱怨相同的错误消息.如果仍然要创建2个对象,则***使用ar进行写入,使用br进行读取. -

Richard, thanks for the suggestion. However, I''ve tried using CArchive* ar with new and delete. Even after you delete the ar pointer, you cannot re-use it. The compiler complains with the same error message. If I am going to have to create 2 objects anyway, I might as well use ar for writing and br for reading. -



如果在删除后重用对象,编译器将不会抱怨,也许您正试图以这种方式重新声明它:



The compiler will not complain if you reuse an object following a delete, perhaps you are trying to redeclare it thus:

CArchive* ar = new Carchive(&f, CArchive::store);
...
delete ar;
CArchive* ar = new Carchive(&f, CArchive::load);
...


而您的第二条语句应写为


whereas your second statement should be written as

ar = new Carchive(&f, CArchive::load);


您已经声明了ar作为指向CArchive对象的指针,因此您不必重新声明它.


You have already declared ar as a pointer to a CArchive object so you must not redeclare it.


您还可以重用一个函数:):
You could reuse a function as well :) :
class CYourArray
{
...
  static LPCTSTR sm_lpszDefFileName;
...
public:
...
  bool ExchangeData(bool bLoad, LPCTSTR lpszFileName = sm_lpszDefFileName);
};