C ++链接列表深层复制构造函数和分配已重载

时间:2014-10-18 02:02:07

标签: constructor linked-list copy operator-keyword

#ifndef LIST
#define LIST

 #include <iostream>
 #include <cstdlib>
 #include <string>

 using namespace std;

typedef string ElementType;


 class List
{
  private:

 class Node
 {

 public:
  ElementType data;
  Node * next;

  Node()
  :data(ElementType()), next(NULL)
  {}

  Node(ElementType initData)
  :data(initData), next(NULL)
  {}

}; // end of Node class         

typedef Node * NodePointer;



  public:
  private:
  NodePointer first;
  int mySize;
  }; // end of List class

这是我重载的任务操作员,我不确定我做错了什么,但我非常沮丧,我已经搜索了网络并阅读了不同的论坛,找不到解决方案来做到这一点,有人可以请我推正确的方向,我省略了所有公共成员函数,因为它们都没有对我重载的赋值和复制构造函数进行操作,我只是想让你们了解我的布局

重载赋值运算符

List & List::operator=(const List &rightSide)
{
if(this != &rightSide)
{
    this->~List();
}

NodePointer ptr = rightSide.first;
NodePointer cptr = ptr;

while(ptr != NULL)
{   
    cptr->next = new Node(ptr->data);
    cptr = cptr->next;
    ptr = ptr->next;
}

return *this;   

}

这是我的复制构造函数

List::List(const List &source)
{
NodePointer ptr = source.first;
NodePointer cptr;

if(ptr == NULL)
{
    cerr << "Bad allocation, empty list" << endl;
    exit(1);
}

while(ptr != NULL)
{
    cptr = new Node(ptr->data);
    cptr->next =    ptr->next;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
    ptr = ptr->next;
 }
 }

0 个答案:

没有答案