作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是我的复制构造函数或者更确切地说是我的重载函数的代码,但我的讲师称它为复制构造函数:
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;
}
}
}
关于c++ - 我的复制构造函数弄乱了列表中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747308/
我是一名优秀的程序员,十分优秀!