2017-02-15 44 views
1

为什么我不能在ostream重载中使用迭代器?重载迭代器的矢量模板的ostream

如果我使用相同的声明使用迭代方法它的作品。

考虑下面的代码:

template <class T> 
class List { 
    template <class U> 
    friend ostream &operator<<(ostream &os, const List<U> &rhs); 
private: 
    vector<T> v; 
}; 

template<class U> 
ostream & operator<<(ostream & os, const List<U>& rhs) 
{ 
    vector<U>::iterator it = rhs.v.begin(); 
    return os; 
} 

int main() 
{ 
    List<int> list; 
    cout << list << endl; 
    return 0; 
} 
+1

如果C++ 11可用于您的目标平台,您可能希望将迭代器的类型声明为'auto',以便编译器可以为您推导正确的类型。在这个词的两个意义上打字要容易得多。 –

回答

2
  1. 注意rhs被声明为参考到const,则rhs.v也将为const,则rhs.v.begin()将返回std::vector<U>::const_iterator,该值不能直接转换为std::vector<U>::iterator

  2. 您应该使用typenamedependent type names

所以将其更改为

typename vector<U>::const_iterator it = rhs.v.begin(); 

BTW:void main()应该int main()

1

尝试用

typename vector<U>::const_iterator it = rhs.v.begin(); 

如果您rshconst,你应该使用const_iterator