我需要为我的程序使用列表,并需要决定是否使用std :: vector或std :: list。 矢量的问题是没有删除方法和列表中没有运算符[]。所以我决定写我自己的扩展std :: list类并重载[]运算符。扩展std :: list
我的代码如下所示:
#include <list>
template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};
#include "myList.h"
template<class T>
myList<T>::myList(void): std::list<T>() {}
template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}
template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}
我可以编译它,但我得到一个链接错误,如果我尝试使用它。有任何想法吗?
你`T运营商[](INT指数);`和`T运营商[](INT及指标);`但是你可能而是使用`T&operator [](int index)`和`const T&operator [](int index)const`。另外,在这些函数内部,你可以'while(index - )`而不是创建一个新变量来跟踪计数。 – Dennis 2013-08-13 22:17:42