Mr.Duy - 1 year ago 93
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* 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;
while (count < tmp)
{
count++;
pNode = pNode->pNext;
}
return pNode->_data;
}

{
//Problem here
}
``````

And file main.cpp

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

`````` 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;
while (count < tmp)
{
count++;
pNode = pNode->pNext;
}
return *pNode;
}

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download