4

我正在尝试实现一个通用(模板)双向链表,类似于 C#.NET 实现。

我想构建一个“捷径”方法来获取具有特定索引的元素,并决定使用下标运算符。我就像在说明中那样做,并想出了这样的东西。

template <typename  T>
class List
{
public:
    T& operator[] (int index) 
    { 
        return iterator->GetCurrentValue(); //iterator is of type Iterator<T> and returns T&
    }
};

但是,当我在我的代码中使用它时:

List<int>* myList = new List<int>();
...
int value=myList[i]; //i is int

我得到一个编译器错误:main.cpp:18: error: cannot convert 'List<int>' to 'int' in initialization在最后一行。

我尝试它返回值,而不是引用,但仍然是同样的错误。

为什么将int返回值解释为List<int>

我正在使用带有 Cygwin gcc-c++ 的 NetBeans。

4

1 回答 1

4

为什么将int返回值解释为List<int>

它不是。 myList是指向 a 的指针List,它不是 aList本身。你需要使用(*myList)[i].

在这种情况下,您不太可能真的需要动态分配,所以我的建议是不要使用指针,也不要使用new.

于 2012-07-06T00:29:21.303 回答