【问题标题】:My copy constructor is messing up the first element in my list我的复制构造函数弄乱了列表中的第一个元素
【发布时间】:2014-02-13 06:59:42
【问题描述】:

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

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 是否正在停止成功复制。

【问题讨论】:

  • 复制构造函数完全不同,它不会释放以前使用的内存。
  • 这就是副本出错的原因吗?
  • 您展示的函数不是复制构造函数,而是复制赋值运算符。
  • 哦,我希望你的Node 构造函数正确地将link 设置为零(即NULL)。
  • 第三,top->link = s.top->link;这行可以去掉。

标签: c++ linked-list stack


【解决方案1】:

我在下面的代码中添加了我认为可以解决您的问题的注释。

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

【讨论】:

  • 那么top->data = newP 在标记为问题的行上方就足够了吗?
  • 同样在您编辑后它会正确复制,但列表的大小仍然无法正确打印出来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-01
  • 2019-04-10
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
相关资源
最近更新 更多