今天在練習hash table時候,准備采用vetor和list進行實現,當我定義一個模板類的迭代器時候,出現錯誤。於是我在網上找找如何處理這個問題,最終解決了問題,記錄在此以后,便於以后查看。我寫的測試程序如下:
1 #include <iostream> 2 #include <vector> 3 #include <list> 4 using namespace std; 5 6 template <class T> 7 class Test 8 { 9 public: 10 void insert(const T& x) 11 { 12 lists.push_back(x); 13 } 14 void display() 15 { 16 list<T>::iterator iter; //模板類型的迭代器 17 for(iter = lists.begin();iter != lists.end();iter++) 18 cout<<*iter<<" "; 19 cout<<endl; 20 } 21 private: 22 list<T> lists; 23 }; 24 25 int main() 26 { 27 Test<int> t; 28 t.insert(10); 29 t.insert(20); 30 t.insert(30); 31 t.insert(40); 32 t.display(); 33 return 0; 34 }
編譯程序時候提示如下錯誤:在第16 行 error: need 'typename' before 'std::list<T>::iterator' because 'std::list<T>' is a dependent scope|
提示的意思是說在list<T>前面需要用typename限定一下,因為編譯器不知道list<T>::iterator是代表一個類型。於是下將16行代碼:
list<T>::iterator iter; 改為 typename std::list<T>::iterator iter;
程序順利通過編譯。參考:http://blog.csdn.net/markman101/article/details/7172918
