我有 2 个班级,名为女人和男人。他们已经注册了流媒体系统。Woman 类有一些属性,最重要的是其中有一个 Man 类的实例。使用 TMemoryStream 和 TStringStream 类,我能够通过 TmemoryStream 类的 WriteComponent 和 ReadComponent 方法检索 Woman 但 Man* 的所有属性。实际上编译器会抛出异常,原因是 Man* 为 NULL 并且未正确加载。在我的程序中,我需要加载所有属性,包括简单数据类型和其他编写类的实例。请给我建议如何正确加载 Woman 对象,以便 Man* 不再为 NULL。这是我的代码片段。
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
#include <memory>
#include <iostream>
#include <conio.h>
#include <string>
#pragma argsused
using namespace std;
class Man : public TComponent
{
private:
double fMoney;
public:
__fastcall Man(TComponent* _Owner,double InMoney)
: TComponent(_Owner)
{
fMoney = InMoney;
}
__published:
__property double Money = {read=fMoney, write=fMoney};
};
class Woman : public TComponent
{
private:
int fAge;
UnicodeString fMyName;
Man* fManInClass;
public:
__fastcall Woman(TComponent* _Owner, int InAge, UnicodeString InName)
: TComponent(_Owner)
{
fAge = InAge;
fMyName = InName;
fManInClass = new Man(this, 0);
}
__published:
__property int Age = {read=fAge, write=fAge};
__property UnicodeString MyName = {read=fMyName, write=fMyName};
__property Man* ManInClass = {read = fManInClass, write = fManInClass};
};
void RegisterClassesWithStreamingSystem(void)
{
#pragma startup RegisterClassesWithStreamingSystem
Classes::RegisterClass(__classid(Man));
Classes::RegisterClass(__classid(Woman));
}
int _tmain(int argc, _TCHAR* argv[])
{
Woman* FirstWoman = new Woman(NULL, 25, "Anjelina");
FirstWoman->ManInClass->Money = 2000;
UnicodeString as;
auto_ptr<TMemoryStream> MStr(new TMemoryStream);
auto_ptr<TStringStream> SStr(new TStringStream(as));
MStr->WriteComponent(FirstWoman);
MStr->Seek(0, soFromBeginning);
ObjectBinaryToText(MStr.get(), SStr.get());
SStr->Seek(0, soFromBeginning);
as = SStr->DataString;
auto_ptr<TMemoryStream> pms(new TMemoryStream);
auto_ptr<TStringStream> pss(new TStringStream(as));
TComponent *pc;
ObjectTextToBinary(pss.get(), pms.get());
pms->Seek(0, soFromBeginning);
pc = pms->ReadComponent(NULL);
Woman* AWoman = dynamic_cast<Woman*>(pc);
cout << AWoman->Age << endl;
cout << AWoman->MyName.c_str() << endl;
cout << AWoman->ManInClass->Money << endl; // AWoman->ManInClass is NULL -> Exception
delete FirstWoman;
pc->Free();
getch();
return 0;
}