我正在尝试实现一个通用(模板)双向链表,类似于 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>
?
我将 NetBeans 与 Cygwin gcc-c++ 结合使用。
最佳答案
Why is it interpreting
int
return value asList<int>
?
不是。 myList
是指向 List
的指针, 它不是 List
本身。你需要使用 (*myList)[i]
.
在这种情况下你不太可能真的需要动态分配,所以我的建议是不要使用指针,也不要使用 new
.
关于c++ - 在模板类中重载下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11354353/