我需要爲我的程序使用列表,並需要決定是否使用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