2009-10-28 45 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  (!!!)