【发布时间】:2016-10-04 20:35:32
【问题描述】:
我目前正在为双向链表类编写复制构造函数/赋值运算符,但遇到了问题。
双链表.h
#include <cstdlib>
#include <iostream>
using namespace std;
class DoublyLinkedList; // class declaration
// list node
class DListNode {
private: int obj;
DListNode *prev, *next;
friend class DoublyLinkedList;
public:
DListNode(int e=0, DListNode *p = NULL, DListNode *n = NULL)
: obj(e), prev(p), next(n) {}
int getElem() const { return obj; }
DListNode * getNext() const { return next; }
DListNode * getPrev() const { return prev; }
};
// doubly linked list
class DoublyLinkedList {
protected: DListNode header, trailer;
public:
DoublyLinkedList() : header(0), trailer(0) // constructor
{ header.next = &trailer; trailer.prev = &header; }
DoublyLinkedList(const DoublyLinkedList& dll); // copy constructor
~DoublyLinkedList(); // destructor
DoublyLinkedList& operator=(const DoublyLinkedList& dll); // assignment operator
// return the pointer to the first node
DListNode *getFirst() const { return header.next; }
// return the pointer to the trailer
const DListNode *getAfterLast() const { return &trailer; }
// return if the list is empty
bool isEmpty() const { return header.next == &trailer; }
int first() const; // return the first object
int last() const; // return the last object
void insertFirst(int newobj); // insert to the first of the list
int removeFirst(); // remove the first node
void insertLast(int newobj); // insert to the last of the list
int removeLast(); // remove the last node
};
// output operator
ostream& operator<<(ostream& out, const DoublyLinkedList& dll);
这是一个补充头文件,其中同时声明了节点和链表类。我注意到 DoublyLinkedList 的受保护类成员(标头和尾标)不是 DListNode 指针,而是实际的 DListNode 值;稍后会详细介绍。
我在 DoublyLinkedList.cpp 中的复制构造函数
DoublyLinkedList::DoublyLinkedList(const DoublyLinkedList& dll)
{
// Initialize the list
header.next = &trailer; trailer.prev = &header;
DListNode* iter = dll.header; // PROBLEM LINE
if (this != &dll) {
while (iter != nullptr) {
insertLast(iter->obj);
iter = iter->next;
}
}
}
我尝试了很多不同的方法来解决这个问题,无论是否编辑头文件。我无法将 header 和 trailer 更改为 DListNode*,因为它们不允许更改,并且将 iter 更改为非指针意味着我无法遍历链表;所以我现在陷入了僵局。因为我无法更改操作数的数据类型,所以我不确定如何修复该错误。我认为这可能与作为常量引用传递的 dll 有关,但即使摆弄它也没有多大作用。我已经看了几个小时了,但似乎无法让它工作。提前感谢您的帮助!
【问题讨论】:
-
'DListNode const* iter = &dll.header;'怎么样
标签: c++ linked-list copy-constructor doubly-linked-list