質問

I am trying to create class Person with pointers to spouse(Person object) and table of children(Person objects). This class implements marriage(operator+=), divorce(method) and creating new children(operator++):

class Person{
private:
    char* name;
    int sex;
    Person* spouse; 
    Person* children[5];
public:
    Person();
    Person(const Person&);      
    Person & operator =(const Person&);
    Person & operator +=(Person&);//marriage
    Person & operator ++();//new children
    void divorce();//divorce
    Person::~Person();
}

I created destructor which deletes children whenever there is no spouse:

Person::~Person(){
    if (name !=NULL)
        delete [] name;
    name=NULL;

    if (spouse!=NULL)
        spouse->spouse =NULL;
    else{
        for (int i=0; i<5;i++){
            if (children[i]!=NULL)
                delete children[i];
            children[i]=NULL;
            }
    }
}

I do not know if my copy constructor and operator= should create another instances of spouse and children. I tried to do this but I was stack in infinite reference. Is it possible to create a copy of Person object with properly assigned spouse and children?

Thanks in advance for any comments and suggestions Elkhunter

役に立ちましたか?

解決 2

Your problem is that you're trying to recursively handle intertwined relationships. When a Husband has a Wife, and both delete the other, you're bound to get stuck in recursive hell of course.

Instead, keep the references as pointers, and do not delete any of them in the destructor - it's simply not the responsibility of the class. Imagine when a real life husband dies, does his wife also die automatically?

Just keep a separate std::vector of Person instances as the 'master catalogue' of people in your 'world', and let them reference eachother lazily through their relationships. Puts all the deletion misery in one extremely non-recursive place, and solves all issues.

他のヒント

I think that your designing it wrong way. Class Person should have preferably only one well defined responsibility. Right now, it's representing at least two separate concepts - a person and a family. Consider splitting those two concepts into separate types - it should make it easier to implement it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top