【问题标题】:Overloading subscript operator in a template class在模板类中重载下标运算符
【发布时间】:2012-07-06 10:46:48
【问题描述】:

我正在尝试实现一个通用(模板)双向链表,类似于 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&lt;int&gt;' to 'int' in initialization 在最后一行。

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

为什么将int返回值解释为List&lt;int&gt;

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

【问题讨论】:

  • 该列表通常不会重载 operator[] 因为它不是随机访问容器。此外,还有 std::list 或 std::vector 是您可能想要使用的现有标准模板类。此外,您的索引值似乎被忽略了。他的目的是什么?
  • 我会调查 std::list,谢谢你的建议。使用了index 值,我只是剥离了放置在这里的不必要代码。即使我做了int i=5; return i;,它也不起作用,所以我认为其余的代码并不重要。

标签: c++ generics operator-overloading


【解决方案1】:

为什么将int返回值解释为List&lt;int&gt;

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

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

【讨论】:

  • 只是为了澄清 Oli 对那些不熟悉 C++ 的人的最后评论。这意味着将List&lt;int&gt;* myList = new List&lt;int&gt;(); 替换为List&lt;int&gt; myList;
  • 谢谢。需要一点时间来适应 C++。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2016-06-21
  • 2012-02-07
  • 2016-04-21
  • 2013-03-24
  • 2013-02-05
  • 1970-01-01
相关资源
最近更新 更多