【发布时间】:2017-09-13 18:00:16
【问题描述】:
我有一个 C++ 代码:
#include <iostream>
using namespace std;
struct Node;
typedef Node *NodePtr;
struct Node
{
int Item;
NodePtr Next;
};
class LinkedList
{
public:
LinkedList(); // default constructor
~LinkedList(); // destructor
void AddTail(int); // adds item to tail
private:
NodePtr Head;
};
LinkedList::LinkedList()
{
Head = NULL; //declare head as null
}
//Adding on tail
void LinkedList::AddTail(int Item)
{
NodePtr Crnt;
NodePtr node = new Node;
node->Item = Item;
node->Next = NULL;
//if head is in null declare the added node as head
if (Head == NULL)
{
Head = node;
}
else
{ //set the current to head, move the current node to current next node
Crnt = Head;
while (Crnt->Next != NULL)
{
Crnt = Crnt->Next;
}
//Add item to the tail of the linked list
Crnt->Next = node;
}
}
int main()
{
LinkedList la;
la.AddTail(30);
la.AddTail(60);
la.AddTail(90);
LinkedList lb;
return 0;
}
所以我的问题是如何实现一个复制构造函数(假设在对象 lb 上),该构造函数对列表参数进行深层复制,并添加代码以在空列表和非空列表上测试复制构造函数? 提前致谢。
【问题讨论】:
-
简单的方法应该是迭代要复制的列表并为列表中的每个元素调用
AddTail方法。但是,嘿,如果你想要一个复制构造函数,你会想要一个赋值运算符来配合它。 May I suggest the Copy and Swap Idiom? -
你能把代码贴出来吗?
-
@Patrick,请发布您尝试实现复制构造函数的代码
标签: c++ constructor linked-list destructor copy-constructor