请帮助我理解链表 C++ 中的运算符重载 =

Please help me understand operator overloading = in linked list c++

我有这样的结构-

struct IntNode
{
    int data;                   
    IntNode * next;         
};

并在 class -

    class NodeSLList {
    private:``
        IntNode *head, *tail;
//some other functions
    }

我有一个对象 list1,它包含一个节点很少的链表。我必须从 list1 创建另一个链表 list2。 如何使用函数-

实现此目的
NodeSLList & operator=(NodeSLList &list){}

我无法理解如何在运算符 = 函数中访问 list2,因为我将在 like-

中传递 list1
list2=list1; 

如何访问 list2??

this 将是指向左操作数的指针,在您的情况下为 list2 。要获取 list2 本身,只需使用取消引用运算符 * 取消引用它。即*this

请记住,this 指针指向退出的 class 您正在操作,因此,this->head 或简称 head 是旧列表的成员,它是您想要更改,并且 newList.head 是您必须分配的新列表的成员。

NodeSLList & operator=(NodeSLList &newList)
{
        //Check if there is something to free?
        if(head != NULL) //this->head != NULL
        {                    
                //free head
        } 
        //Assign new one
        head = newList.head; //this->head = newList.head;
        //Other stuff if any
        return this;
}

答案是*this

总之。请不要实现自己的链表。已经有std::list,或者如果你需要一个双向链表std::deque。您需要付出很多努力才能使您的代码与标准库一样高质量,更不用说定义一个同样经过深思熟虑的接口了。

所以如果这是你的学校的四个,写你自己的链表。我们都那样做了。这是练习使用指针编程的好方法。但是请抵制稍后在生产代码中做类似事情的诱惑。我经常看到它,大多数时候它很慢而且效率低下,而且经常有很多错误。

函数(运算符)NodeSLList & operator=(NodeSLList &list) 称为 copy assignment operator。它不创建新对象,而是分配给它们。所以对于你的第一个问题

I have to create another linked list list2 from list1. How do I achieve this using the function...

答案是;你没有。首先你创建一个新对象 list2 然后你可以分配给它。以下代码将首先调用默认构造函数,然后调用复制赋值运算符:

NodeSLList list2;
list2 = list1;

所以实际上 list2 = list1; 是 shorthand for

list2.operator=(list1);

也许这更清楚地表明函数 operator= 用于现有对象,并且正如所有其他答案所指出的那样,您可以通过 *this.[=21= 访问该对象]

顺便说一句,如果你写 NodeSLList list2 = list1;,你会调用 copy constructor,这是另一回事...