简体   繁体   English

linkList复制构造函数和赋值运算符

[英]linkList copy constructor and assignment operator

I'm writing my node and list classes and everything works fine except when I include destructor , copy constructor and the assignment operator functions in the list class, and I don't know what is wrong with them or what I have miss not to include. 我正在编写节点和列表类,并且一切正常,除非我在列表类中包含析构函数,复制构造函数和赋值运算符函数,而且我不知道它们有什么问题或者我错过了什么不包括在内。

linklist::linklist()
    :firstNode(NULL),
    lastNode(NULL),
    nodeCount(0) {}

linklist::~linklist()// destructor
{
    node* current = firstNode;
    while( current != 0 ) {
        node* temp = current->getNextNode();
        delete current;
        current = temp;
    }
    firstNode = 0;
}

linklist::linklist(linklist &L)// copy constructor
{
    firstNode = NULL;
    nodeCount = 0;
    node* temp = L.firstNode;
    for(int i = 0; i < L.getNodeCount(); i++)
    {
        push_back(temp);
        temp = temp->getNextNode();
    }
}

linklist& linklist::operator=(const linklist& L)// overloading assignemnt operator
{
    linklist* LL;
    node* temp = L.firstNode;
    while( temp != NULL ) {
        LL->getLast();
        temp = temp -> getNextNode();
    }
    return *LL;
}

Your assignment should be similar to your copy constructor. 您的分配应类似于您的副本构造函数。 Because they both do almost the same thing. 因为他们几乎都做同一件事。

The difference being you assignment should clear what it in the list(itself) before starting copying the rhs(the other one). 区别在于您要分配的内容应在开始复制rhs(另一个)之前clear列表中的内容(本身)。

And then it should return a reference to itself. 然后它应该返回对自身的引用。 return *this . return *this So that assignments can be chained. 这样就可以链接任务。

linklist& linklist::operator=(const linklist& L)// overloading assignemnt operator
{
    // Check if self assignment
    if (&L == this)
       return *this;

    // clear myself.
    // copy other.
    return *this;
}

You seem to have two issues. 您似乎有两个问题。 First, the destructor deletes all node structures. 首先,析构函数删除所有节点结构。 Any new linked list that copied using the copy constructor would have incorrect data once the original is destroyed. 一旦原始副本被销毁,使用复制构造函数复制的任何新链表将具有不正确的数据。 Second, it's probably better if you copied the node structure using its copy constructor. 其次,如果使用其复制构造函数复制节点结构,可能会更好。 It's hard to say without exact information, but your linked list ctor could look something like: 没有确切的信息很难说,但是您的链表ctor可能类似于:

firstNode = NULL;
nodeCount = 0;
node* temp = L.firstNode;
for(int i = 0; i < L.getNodeCount(); i++)
{
    push_back(new node(*temp));
    temp = temp->getNextNode();
}

This way the new linked list has its own copy of nodes. 这样,新的链表具有自己的节点副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM