链接列表递归复制构造函数的麻烦

时间:2015-11-13 16:48:57

标签: c++ recursion

我很难弄清楚我的递归复制构造函数有什么问题。

我的班级是一个常规未分类的动态链接列表。

struct Node{
    int info;
    Node *next;
};

以下只是查看我将要使用的逻辑的简单方法

class Class{
public:
    //constructor
    Class(){ data = NULL;}

    //copy consturctor
    Class(const Class& second){
        cout << "This is copy constructor" << endl;



        //recursive copy contructor
        Class temp;
        temp.data = second.data;

        if (temp.data == NULL)  return; //base condition
        int x = temp.data->info;
        temp.data = second.data->next;
        insert(x);
        Class::Class(temp);

        //regular copy constructor
        /*if (second.data == NULL){//empty
        data = NULL;
        return;
        }
        Node *temp = second.data;
        Node *location = new Node;
        location->info = temp->info;
        data = location;
        location->next = NULL;
        temp = temp->next;

        while (temp != NULL){
        location->next = new Node;
        location = location->next;
        location->next = NULL;
        location->info = temp->info;
        temp = temp->next;
        }*/

    }   

    //destructor
    ~Class(){
        cout << "This is destructor" << endl;

        //recursive destructor
        /*Node *temp;
        temp = data;
        if (temp == NULL) return;
        else{
        data = data->next;
        delete temp;
        Class::~Class();
        }*/

        //reglar destructor
        Node *temp = data;
        while (data != NULL){
            temp = data;
            data = data->next;
            delete temp;
        }   
    }
    void insert(int x){
        Node *temp = new Node;
        temp->info = x;
        temp->next = data;
        data = temp;
    }
    void print(){
        Node *temp = data;
        while (temp != NULL){
            cout << temp->info;
            temp = temp->next;
        }
        cout << endl;
    }

private:
    Node *data;
};

主要功能:

void main(){

    Class object;

    object.insert(1);
    object.insert(2);
    object.insert(3);
    object.insert(4);
    object.print();

    Class object2 = object;
    object2.print();
}

好的,从我的“很多”实验来看,似乎问题出现在递归完成并且处理开始倒退时。因此,如果这是2个节点,则第3个节点为NULL。由于

,递归完成了
if (temp == NULL) return;

每次完成一个堆栈时都会调用析构函数,对析构函数的第一次调用是NULL对象(第3次和最后一次)的调用,这很好。对析构函数的下一次调用是故障开始的地方。似乎传递给析构函数的数据具有垃圾值。

事实上,复制构造函数中的所有内容都很顺利,因为正确地提取和插入数据。为什么析构函数有问题?

注意:有一个递归析构函数(已注释掉)和一个常规析构函数。他们都工作正常,但我正在使用常规的,以防意外的突发事件。

我还包括并注释掉常规复制构造函数。

提前致谢。

0 个答案:

没有答案
相关问题