2009-10-28 50 views
0

以下不編譯,我不能爲我的生活看到爲什麼!使用列表/迭代器愚蠢編譯錯誤(C++)

#include <list> 
using namespace std; 

list<char> myList; 
list<int>::iterator it; 

it = myList.begin(); 

錯誤:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::list<_Ty>::_Iterator<_Secure_validation>' (or there is no acceptable conversion) 
+0

注意模板相關的錯誤,微軟編譯器會在錯誤消息後行打印模板參數。所以下一行將包含'with [Ty_ = int]和[Ty_ = char]'。 – MP24 2009-10-28 15:58:01

回答

5

發生這種情況是因爲list<char> and list<int>是兩個不同的類。 所以他們的迭代器也是不同的類型。
如果你看的std :: list類的代碼,你會看到類似這樣的:

typedef _Iterator<_SECURE_VALIDATION_DEFAULT> iterator; 

typedef _Iterator<bla_bla_bla> iterator; 

這意味着新的類型是由每個不同的類列表定義。換句話說,每個列表都定義了自己的迭代器類型。

你的代碼改成這樣:

list<char>::iterator it; 
+0

Agg,我不敢相信我沒有看到:-S – Justin 2009-10-28 11:53:04

+2

這通常意味着你需要休息一下;) – alexkr 2009-10-28 11:57:13

3

由於迭代器的類型是不同的:

list<char> myList; // char 
list<int>::iterator it; // int 

當心的列表或任何其他的容器的類型不僅是模板類型參數,但也包括所有其他模板參數。例如:

list<char, MyAllocator> mylist; 
list<char, YourAllocator> yourlist; 
// typeof mylist != type of yourlist  (!!!)