C++ 我的复制构造函数正在弄乱列表中的第一个元素

C++ 我的复制构造函数正在弄乱列表中的第一个元素,c++,linked-list,stack,C++,Linked List,Stack,下面是我的复制构造函数或重载函数的代码,但我的讲师将其称为复制构造函数: void operator=(const Stack& s) { if (s.top == NULL) top == NULL; else { top = new Node; top->link = s.top->link; Node* newP = t

下面是我的复制构造函数或重载函数的代码,但我的讲师将其称为复制构造函数:

void operator=(const Stack& s)
    {
        if (s.top == NULL)
            top == NULL;
        else
        {
            top = new Node;
            top->link = s.top->link;
            Node* newP = top;

                for(Node* curr = s.top->link; curr != NULL; curr = curr->link)
                {
                    newP->link = new Node;
                    newP = newP->link;
                    newP->data = curr->data;
                }
        }
    }
我期望收到的输入将与我得到的输入一起显示在下图中。


据我所知,NULL等于0,因此我想知道我的s.top设置为NULL是否会阻止成功复制。

我已经用我认为可以解决您的问题的注释对下面的代码进行了注释

void operator=(const Stack& s)
{
    if (s.top == NULL)
        top == NULL; // make sure you delete the existing nodes if there are any - this looks like a leak
    else
    {
        top = new Node; 
        top->link = s.top->link; // you need to remove this line you will allocate a new link later
        top->data = s.top->data; // this is the missing line messing with your first node
        Node* newP = top;

        for (Node* curr = s.top->link; curr != NULL; curr = curr->link)
        {
            newP->link = new Node; 
            newP = newP->link; // here's your issue - on the first iteration you're stepping over the first node but you never set the data for it
            newP->data = curr->data;
        }
    }
}

复制构造函数是完全不同的,它不会释放以前使用的内存。这就是复制出错的原因吗?您显示的函数不是复制构造函数,而是复制赋值运算符。哦,我希望您的
节点
构造函数正确地将
链接
设置为零(即
NULL
)。第三,行
top->link=s.top->link可以删除。因此,在标记为问题的行上方的
top->data=newP
就足够了吗?编辑后,它也可以正确复制,但列表的大小仍然无法正确打印出来