C++ 在单链表中复制构造函数和赋值运算符
这是我昨天在作业中用单链表提问的后续问题。我一直在努力创建复制构造函数,直到最后才使用赋值操作符,因为我认为它们与implement有些相似。我想我有创建复制构造函数的步骤:C++ 在单链表中复制构造函数和赋值运算符,c++,linked-list,copy-constructor,assignment-operator,C++,Linked List,Copy Constructor,Assignment Operator,这是我昨天在作业中用单链表提问的后续问题。我一直在努力创建复制构造函数,直到最后才使用赋值操作符,因为我认为它们与implement有些相似。我想我有创建复制构造函数的步骤: 使用新列表作为参数创建新节点 遍历列表,将每个节点从列表1添加到列表2(我有一个add函数,我认为这会有所帮助?) 执行此操作时,通过列表2递增,以便正确添加每个节点 请纠正我的任何步骤(或者我需要扩展这些步骤)。为了理解我必须要做的事情,我查看了很多在Google上找到的代码,但是我的实现和理解仍然是模糊的。以下是我迄今
lst2.add(ptr->data)的第5行
它会调用add
函数并用val
替换ptr->data
?只是想知道这样写是否不会带来任何错误
编辑:我也忘了发布这个代码片段。它显示了我创建两个整数列表并试图使iList2=iList代码>以便调用复制构造函数。不过,我想我可能做错了
void intList() {
SLList<int> iList;
cout << "\nNow showing integer list..." << endl;
iList.add(5);
iList.add(6);
iList.add(6);
iList.add(3);
iList.add(4);
SLList<int> iList2 = iList;
iList.print();
iList2.print();
}
你用std::list
或std::forward\u list
来代替它怎么样?我忘了提到这是一个赋值,我相信我们必须通过赋值和重新赋值指针来解决它。不确定是否允许这两种情况。您添加的方向错误。复制构造函数的参数是源,而不是目标。“对象”(this)是目标,而不是源。那lst2.add
调用应该是add
,循环应该是lst2.head
。如前所述,这甚至不可能编译,更不用说正确运行了,因为add
不是const
函数,lst2
是const对象。@WhozCraig Oh。。因此,for(Node*ptr=head;
应该是for(Node*ptr=lst2.head;
)?我是否也必须将ptr=ptr->next
更改为ptr=lst2->next
?
template<typename T>
void SLList<T>::add(const T& val) {
Node *prev = head;
for (Node *ptr = head->next; ptr != NULL; ptr = ptr->next) {
prev = ptr;
if (ptr->data == val) {
return;
}
}
prev->next = new Node(val);
}
void intList() {
SLList<int> iList;
cout << "\nNow showing integer list..." << endl;
iList.add(5);
iList.add(6);
iList.add(6);
iList.add(3);
iList.add(4);
SLList<int> iList2 = iList;
iList.print();
iList2.print();
}
template<typename T>
const SLList<T>& SLList<T>::operator=(const SLList & rhs) {
cout << "\nCalling assignment operator..." << endl;
// Step (1) Delete the existing list
while (head != NULL) {
Node *temp = head;
head = head->next;
delete temp;
}
// Step (2) Build a new, copy list
if (this != &rhs) {
for (const Node *ptr = rhs.head; ptr != NULL; ptr = ptr->next) {
add(ptr->data);
}
}
return *this;
}