gpt4 book ai didi

c++ - 我的复制构造函数弄乱了列表中的第一个元素

转载 作者:行者123 更新时间:2023-11-28 07:06:03 25 4
gpt4 key购买 nike

下面是我的复制构造函数或者更确切地说是我的重载函数的代码,但我的讲师称它为复制构造函数:

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;
}
}
}

我希望收到的输入将与我收到的输入一起显示在下面的图片中。 enter image description here

据我了解 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;
}
}
}

关于c++ - 我的复制构造函数弄乱了列表中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com