1
我一直在試圖約2周使用其writecomponent
方法TMemoryStream
對象寫信TComponent
派生的任意類的一個對象,並再次使用readcomponent
方法檢索該對象讀取組件。雖然我認爲這是一件容易的事,但我無法讓它正常工作。實際上沒有編譯錯誤,但對象的屬性沒有正確加載。請幫我看看我做錯了什麼。這是我的代碼片段。如何編寫和使用TMemoryStrream
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
#include <memory>
#include <iostream>
#include <conio.h>
#pragma argsused
using namespace std;
class Woman : public TComponent
{
private:
int Age;
public:
UnicodeString Name;
Woman(TComponent* _Owner, int InAge, UnicodeString InName)
: TComponent(_Owner)
{
Age = InAge;
Name = InName;
}
int GetAge()
{
return Age;
}
};
void RegisterClassesWithStreamingSystem(void)
{
#pragma startup RegisterClassesWithStreamingSystem
Classes::RegisterClass(__classid(Woman));
}
int _tmain(int argc, _TCHAR* argv[])
{
Woman* FirstWoman = new Woman(NULL, 25, "Anjelina");
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;
AWoman = dynamic_cast<Woman*>(pc);
cout << AWoman->GetAge() << endl;
cout << AWoman->Name.c_str() << endl;
FirstWoman->Free();
pc->Free();
getch();
return 0;
}
感謝親愛的雷米。我喜歡你。有效。你是個天才 –