Joshua Haddad
Joshua Haddad

Reputation: 31

Is it possible to use overloaded operators with "this" in instance methods?

I am making a linked list and one of the methods required is to print the data of the linked list. I attempted to use a loop and overloaded [] operators (returns the data type T of the indexed node) to print the list like so:

for(unsigned int i = 0; i < length; i++){
    cout << this[i] << endl;
}

The compiler is throwing an error that cout does not support type const LinkedList<T>, despite this code working in my test file:

LinkedList<int> newList = LinkedList<T>();
populateList
cout << newList[5] << endl;

I suspect my syntax for using the overloaded brackets operator with this is incorrect, could someone elaborate why?

EDIT2:

Deleted raw code snippet as to avoid any potential academic honesty issues.

Upvotes: 0

Views: 45

Answers (1)

Brian Bi
Brian Bi

Reputation: 119372

You have to write (*this)[i], since the overloaded [] operator belongs to the class itself, but this is just a pointer.

The expression this[i] is valid, but in general p[i] where p is a pointer is interpreted as *(p + i), so it's not doing what you want it to do.

Upvotes: 3

Related Questions