简体   繁体   中英

Array of pointers to pointers

I need to have an array of objects that I can pass as arguments to other objects.

Let's say, I need to have an array of People objects, and I need to pass them as arguments to Group objects. Then I need to replace a "People" object somewhere in the code, and all groups that contained the previous "People", now use the new "People" object.

Eg.:

People** peoples[100];
Group* groups[10];

peoples[0] = new Male();
peoples[0]->SetHeight(190);
peoples[1] = new Male();
peoples[1]->SetHeight(191);
peoples[2] = new Male();
peoples[2]->SetHeight(192);
peoples[3] = new Male();
peoples[3]->SetHeight(193);
peoples[4] = new Male();
peoples[4]->SetHeight(194);

groups[0] = new Group();
groups[0]->SetMembers(peoples[0], peoples[1], peoples[2]);
groups[1] = new Group();
groups[1]->SetMembers(peoples[0], peoples[3], peoples[4]);

delete peoples[0];
peoples[0] = new Female();
peoples[0]->SetHeight(170);

(btw: Male and Female inherits People)

The goal is that at the end, groups 0 and 1 have the "Female height 170" object as first member instead of the initial "Male height 190" object. As an evidence, the place in the program where the "peoples[0]" object is deleted and replaced by the Female object doesn't know which groups do contain it, so I think pointers is the right way to go.

But, "peoples" is an array of pointers to pointers.

How do I instanciate the intermediary pointer ?

Should be something like:

Pointer p = new Pointer();
peoples[0] = p;
Male* m = new Male();
p.address = f;

then

Female* f = new Female();
delete peoples[0].address;
peoples[0].address = f;

For sure it's not the right code, I'm a bit stuck on how to achieve this.

Store the pointer to the pointer-pointer of People in your Groups instead.

typedef struct Group {
    People ***members;
    ...
} Group;

...

groups[0] = new Group();
groups[0]->SetMembers(&peoples[0], &peoples[1], &peoples[2]);

This may get pretty messy ahead. It may be tempting at first, but I strongly recommend you to find an alternative way of doing what you want.

I ended up using encapsulation for the intermediary object :

class PeopleContainer
{
  public:
    PeopleContainer() {}
    PeopleContainer(People* myPeople) { ptr = myPeople; }
    People* ptr;
};

Works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM