Mr.Duy Mr.Duy - 1 month ago 14
C++ Question

How to use operator [] with operator =?

I have a problem with the alignment of the operator [] and operator =.
I can't understand to write function LinkedList LinkedList::operator=(const int& n) accurately. it does not look like any operator = that I met through.
Please help me understand the nature of it (together with the code as possible). Thank very much!

file .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
}


And file main.cpp

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

Answer
 l[-1] = 9000;
    l[4] = 2000;
    l[100] = 10000;

On this line of codes, LinkedList::operator=(const int& n) will not be called, because LinkedList::operator[](const int& i) returns a reference to int.

what you want to do is to return a Node on your LinkedList::operator[](const int& i), and define your own operator= there.

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;
          }
    }

Edit:
Make sure you place pNode somewhere where it can be deleted later to avoid memory leak.