how shall I reload several obejcts that dependent on each other?

A

Andy

Hi,

I am trying to find a way to store objects and reload later so as to
restore the preserved objects. But now I come to the problem that,if
objects dependent on each other, how shall I recontruct the dependent
information in reloading? As for the following code, the reloading
processs will result in a infinite recursion.

#include <iostream>
#include <string>
#include "Archive.hh"
using namespace std;


class B;

class A{
public:
int id;
string content;
B * ptr;

public:
void load_from(Archive& ar);
void store_to(Archive& ar);
void print()
{
cout << "this = " << this << ":"
<< "[content = " << content
<< ", ptr = " << ptr
<< "]\n";
}
};


class B
{
public:
int id;
string content;
A * ptr;
int val;

public:
void load_from(Archive& ar){
ar >> id >> content >> val;
ptr = new A;
ptr->load_from(ar);
}

void store_to(Archive& ar){
ar << id << content << val;
ptr->store_to(ar);
}

void print()
{
cout << "this = " << this << ":"
<< "[content = " << content
<< ", ptr = " << ptr
<< ", val = " << val << "]\n";
}
};



void A::load_from(Archive& ar)
{
ar >> id >> content;
ptr = new B;
ptr->load_from(ar);
}


void A::store_to(Archive& ar)
{
ar << id << content;
ptr->store_to(ar);
}



int main()
{
A * pa = new A, *pc;
B * pb = new B, *pd;


pa->content = "class A object";
pb->content = "class B object";

pb->val = 1020;

pa->ptr = pb;
pb->ptr = pa;

pa->print();
pb->print();

Archive ar;

pa->store_to(ar);
pb->store_to(ar);


///////////////////////////////

ar.rewind();

pc = new A;
char ptr[123455];
pd = new B;

pc->load_from(ar);
pd->load_from(ar);


pc->print();
pd->print();

delete pa;
delete pb;
delete pc;
delete pd;
}

Thanks.

Andy
 
A

Abecedarian

Andy said:
I am trying to find a way to store objects and reload later so as to
restore the preserved objects. But now I come to the problem that,if
objects dependent on each other, how shall I recontruct the dependent
information in reloading? As for the following code, the reloading
processs will result in a infinite recursion.

#include <iostream>
#include <string>
#include "Archive.hh"

It would be interesting to know what "Archive.hh" is?
int main()
{
A * pa = new A, *pc;
B * pb = new B, *pd; ....
pc = new A; ....
pd = new B; ....
delete pa;
delete pb;
delete pc;
delete pd;
}

BTW, why do you create these objects on the heap and delete them later?
You have been using Java, right?

::A::
 
A

Andy

This is an experimental file. Since in the real project I want to put
those objects in heaps, I use pointer here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top