【问题标题】:Assignment Operator for Doubly Linked List in C++C++中双向链表的赋值运算符
【发布时间】:2016-10-16 19:22:54
【问题描述】:

我无法理解赋值运算符的概念,或者至少成功地创建它们。

复制构造函数对我来说不是问题;这是我的工作:

//copy constructor
Set::Set(const Set &rhs){
    _head = rhs._head;
    _tail = rhs._tail;

    //null, basically this object is 0
    if(rhs._head == NULL){
        _head = NULL;
        _tail = NULL;
        _size = 0;
    }else{
        _head = new Elem(*rhs._head);
        _tail = new Elem(*rhs._tail);
        _size = rhs._size;

        Elem *prev = NULL;
        Elem *curr = _head;
        Elem *otherCurr = rhs._head;
        int counter = 0;
        while(otherCurr->next != NULL){
            curr->next = new Elem(*otherCurr->next);
            curr->next->prev = curr;


            curr = curr->next;
            otherCurr = otherCurr->next;
        }

        //now that we are done lets setup the tail
        _tail->prev = curr;
        curr->next = _tail;

    }

}

我在阅读示例代码,看到有人使用#include <algorithm> 库来实现它。我试过了,但似乎根本不起作用。

//assignment operator
Set& Set::operator=(const Set &rhs){
    Set temp(rhs);
       std::swap(temp._head,_head);
       std::swap(temp._tail, _tail);
       return *this;

}

但是上面的代码不能正常工作。真的很难掌握如何制作赋值运算符的概念。我认为它基本上与您想要将值从一个复制到另一个相同。但显然不是。如果有人可以建议我如何让它发挥作用,那就太好了。

关于我的班级的一些更一般的信息,a _heada _tail 指向列表的开头和结尾。虚拟元素。

这是对象的结构:

  struct Elem {
        ELEMENT_TYPE info;
        Elem *prev, *next;
    };
    Elem *_head, *_tail;
    int _size;

【问题讨论】:

  • 否决minimal reproducible example。主题:复制构造函数中的整个潜在伤害世界:_head = rhs._head; _tail = rhs._tail;Off 主题:注意下划线前缀。它们通常保留供内部图书馆使用。你在这里应该是安全的,但是在全局范围内这样做或在下划线后面加上大写字母,你可能会遇到麻烦。
  • 叹息,感谢您的反对。大帮助
  • 为什么要手动实现链表而不是使用std::list

标签: c++ linked-list assignment-operator


【解决方案1】:

我发现您的复制构造函数存在两个问题(甚至没有尝试进一步挖掘):

  1. tail 的用途是什么?它似乎不需要,或者没有正确使用。
  2. 您的复制循环似乎在 otherCurr->next 为 NULL 时停止。但是您将 curr->next 指向尾部的最后一个元素。这很可能意味着您将 1 个元素复制到您的集合之外,甚至更糟(因为您可能无法正确初始化 tail 查看它的定义),您正在尝试复制随机位置,这将导致您的程序迟早崩溃。

【讨论】:

  • 不,如此处所示,它没有。如果确实如此,您可能(不)幸运。你没有考虑你的类不变量,因此你没有在不同的构造函数中初始化它们。
猜你喜欢
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2020-06-26
  • 1970-01-01
相关资源
最近更新 更多