C++ C++;-如何在析构函数中删除子类

C++ C++;-如何在析构函数中删除子类,c++,class,destructor,C++,Class,Destructor,下面是一个类定义: class Person { private: char* name; int numChildren; Person** childrenList; public: Person(char* name); ~Person(); }; 在Person::Person()构造函数中,它将根据构造函数参数设置人员的名称,然后为每个子级创建Person对象,每个子级可能有其他子级。让我们举一个例子,在我运行这个之后:Person*me=ne

下面是一个类定义:

class Person {
private:
    char* name;
    int numChildren;
    Person** childrenList;
public:
    Person(char* name);
    ~Person();
};
Person::Person()
构造函数中,它将根据构造函数参数设置人员的名称,然后为每个子级创建
Person
对象,每个子级可能有其他子级。让我们举一个例子,在我运行这个之后:
Person*me=newperson(“Alex”),将创建以下结构:
即,如果创建了
me
me
的子项也将递归创建

但是我在
Person::~Person()
析构函数中遇到了问题。在析构函数中,它应该删除所有动态对象,包括名称和每个子对象。以下是我的尝试:

Person::~Person() {
    for (int i = 0; i < numChildren; i++) {
        // go inside each child
    }
    delete[] this->name;
    delete[] childrenList;
}
Person::~Person(){
for(int i=0;i名称;
删除[]儿童名单;
}
但是我不知道如何进入每个孩子的内部,析构函数没有参数


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

只需
删除
每个孩子,然后再
删除[]孩子列表

Person::~Person()
{
    for (int i = 0; i < numChildren; i++) {
        delete childrenList[i];
    }
    delete[] childrenList;
    ...
}
Person::~Person()
{
for(int i=0;i
当使用类似于
个人**儿童列表的双poiner时,您必须执行以下操作才能分配和删除它:

    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;
无符号len1=100;
无符号len2=100;
//childrenList是指向指针数组的指针
人员**儿童列表=空PTR;
//创建一个包含未分配人员指针的数组,注意“*”
儿童名单=新人*[len1];
//分配数组中的所有指针
对于(大小i1=0;i1
您可以将其放入析构函数中:

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;

}
Person::~Person()
{
//删除数组中的所有指针
对于(大小i1=0;i1
但使用“2d”std::vector可以更轻松地完成整个过程:

vec<vec<Person>> childrenList;
vec儿童列表;
这样的2d向量有自己的语法,但它比“裸”指针/数组更简单,也不容易出错-
PS:我没有尝试编译或运行这个示例。

通常,答案是“不要自己分配内存,而是使用字符串、向量和智能指针,它们会自动清理”。您是否需要(如教授)使用new/delete?也就是说,如果你只是
delete
该循环中的每个子循环,它将调用该子循环的析构函数,并启动你正在寻找的递归链。@parktomi好吧,它来自家庭作业,我对它做了一点修改,不允许修改类定义,所以我必须使用new/delete。在删除第一个时,是否有一些方法可以删除所有内容?您的构造函数是什么样子的?(有时析构函数看起来像“反向”的构造函数。)你就快到了。如果在堆栈上声明根用户,将自动调用析构函数。如果您在堆上用
new
声明了root Person,则在
delete
时将调用析构函数。因此,如果删除第一个,它将调用析构函数。然后,如果析构函数删除该循环中
childrenList
中的每个条目,它将不断地为每个子级调用析构函数,直到剩下的指针为NULL或列表为空。@parktomi您能解释一下何时调用子级析构函数吗?你的意思是如果我只是
删除childrenList
,每个children析构函数都会被调用吗?