Search code examples
c++operator-overloadingdoubly-linked-listrandom-access

C++: Using predeclared operator[] in another method


I am trying to use a predeclared operator[] in another method of the same class. However, I have no idea how to proceed. Funny part is that I don't even know how to google it :(. Please, advise...

This is part of a doubly-linked-list - I want to enable Array behavior in it (I know - not good :)).

Code snippet:

template <typename T>
T& DLL<T>::operator[](int i) const{
  Node <T>*n = this->head;
  int counter = 0;
  while (counter > i) {
    n = n->next;
    counter++;
  }
  return n->next->val;
}

template <typename T>
T& DLL<T>::at(int i) const throw (IndexOutOfBounds) {
  if (i < 0 || i >= elemNum) {
    throw IndexOutOfBounds("Illegal index in function at()");
  }
  // I want this part to use the predeclared operator 
  // obviously this is not right...
  return this[i];  // Why u no work?!??!?
}

Solution

  • Try calling this->operator[](i). This should get you the desired result.

    EDIT

    As WhozCraig said: (*this)[i] works as well and is probably more elegant.