C++ - 如何在析构函数中删除 sub-classes

C++ - how to delete sub-classes in destructor

这是一个 class 定义:

class Person {
private:
    char* name;
    int numChildren;
    Person** childrenList;
public:
    Person(char* name);
    ~Person();
};

Person::Person()构造函数中,会根据构造函数参数设置人名,然后为每个child创建Personobject,每个 child 可能有其他 children。举个例子,在我 运行 这个:Person* me = new Person("Alex"); 之后,将创建以下结构: 即如果me被创建,me的children也会被递归创建

但是我在 Person::~Person() 析构函数中遇到了麻烦。在析构函数中,它应该删除所有动态 object,包括名称和每个 child。这是我的尝试:

Person::~Person() {
    for (int i = 0; i < numChildren; i++) {
        // go inside each child
    }
    delete[] this->name;
    delete[] childrenList;
}

但是我不知道如何进入每个child,而且析构函数没有参数。

谁能给我一些提示?谢谢!

在你 delete[] childrenlist 之前 delete 每个 child :

Person::~Person()
{
    for (int i = 0; i < numChildren; i++) {
        delete childrenList[i];
    }
    delete[] childrenList;
    ...
}

当使用像 Person** childrenList 这样的双指针时,你必须这样做来分配和删除它:

    unsigned len1 = 100;
    unsigned len2 = 100;

    //  childrenList is a pointer to a an array of pointers
    Person** childrenList = nullptr;

    // create an array with UNALLOCATED Person pointers, note the "*"
    childrenList = new  Person*[len1];          

    // allocate all the pointers in the the array
    for (size_t i1 = 0; i1 < len1; i1++)
        childrenList[i1] = new Person;


    // delete all the pointer in the array
    for (size_t i1 = 0; i1 < len1; i1++)
        if (childrenList[i1])
            delete childrenList[i1];        

    // delete the array itself
    delete[] childrenList;

你可以把它放在你的析构函数中:

Person::~Person()
{
// delete all the pointer in the array
        for (size_t i1 = 0; i1 < len1; i1++)
            if (childrenList[i1])
                delete childrenList[i1];        

        // delete the list itself
        delete[] childrenList;

}

但是如果使用“2d”,整个事情会变得更容易 std::vector:

vec<vec<Person>> childrenList;

这样的二维向量有自己的语法,但它比 "bare" pointers/arrays 更容易出错。- PS:我没有尝试编译或 运行 这个例子。