I am trying to implement a generic (template) bidirectional linked list, similar to C#.NET implementation.
I wanted to build a “short cut” method to get at element with a certain index and decided to go with the subscript operator. I did just like in the instructions, and came up with something like this.
template <typename T>
class List
{
public:
T& operator[] (int index)
{
return iterator->GetCurrentValue(); //iterator is of type Iterator<T> and returns T&
}
};
however when I get to use this in my code:
List<int>* myList = new List<int>();
...
int value=myList[i]; //i is int
I get a compiler error: main.cpp:18: error: cannot convert 'List<int>' to 'int' in initialization on the last line.
I tried it to return value, not reference, but still the same error.
Why is it interpreting int return value as List<int>?
I am using NetBeans with Cygwin gcc-c++.
It’s not.
myListis a pointer to aList, it’s not aListitself. You’d need to use(*myList)[i].It’s quite unlikely that you really need dynamic allocation in this scenario, so my suggestion would be to not use a pointer, and to not use
new.