如何将运算符[]与运算符=一起使用

How to use operator [] with operator =?

本文关键字:运算符 一起      更新时间:2023-10-16

我对运算符[]和运算符=的对齐有问题。我无法理解如何准确地编写函数LinkedList LinkedList::operator=(const int&n(。它看起来不像是我通过电话认识的任何接线员。请帮助我理解它的性质(尽可能连同代码(。非常感谢!

文件.h

    class LinkedList
    {
    private:
        Node* pHead;
        Node* pTail;
        int curN;
    public:
        int& operator[](const int& i);
        LinkedList operator = (const int& n);//
    };

file.cpp

  int& LinkedList::operator[](const int& i)
  {
        int tmp;
        if (i < 0)
            tmp = 0;
        else if (i > this->curN)
            tmp = this->curN - 1;
        else
            tmp = i;
        int count = 0;
        Node* pNode = this->pHead;
        while (count < tmp)
        {
            count++;
            pNode = pNode->pNext;
        }
        return pNode->_data;
    }
    LinkedList LinkedList::operator=(const int& n)
    {
        //Problem here
    }

和文件main.cpp

 int main()
    {
        srand(1234);
        LinkedList l;
        l[-1] = 9000;
        l[4] = 2000;
        l[100] = 10000;
        cout << l << endl;
    }
 l[-1] = 9000;
    l[4] = 2000;
    l[100] = 10000;

在这行代码中,不会调用LinkedList::operator=(const int& n),因为LinkedList::operator[](const int& i)返回对int的引用

您想要做的是在LinkedList::operator[](const int& i)上返回一个Node,并在那里定义自己的operator=

Node& LinkedList::operator[](const int& i)
  {
        int tmp;
        if (i < 0)
            tmp = 0;
        else if (i > this->curN)
            tmp = this->curN - 1;
        else
            tmp = i;
        int count = 0;
        Node* pNode = this->pHead;
        while (count < tmp)
        {
            count++;
            pNode = pNode->pNext;
        }
        return *pNode;
    }
///Your node class
    class Node
    {
       public: 
          int _data;
          Node& operator=(const int data)
          {
              _data = data;
              return *this;
          }
    }

编辑:
确保将pNode放置在以后可以删除的位置,以避免内存泄漏

operator=是为对象而不是为其内容而设的。

在这种情况下,LinkedList::operator=(const int& n)被称为:

LinkedList l;
l = 5;

在这种情况下,只调用LinkedList::operator[]

l[4] = 2000;

您的赋值运算符需要在Node类中,而不是列表类中。

您正在指定给一个节点。要调用列表类分配运算符,您必须执行以下操作:

l=LinkedList((;

(但这不是你想要的(