简体   繁体   English

重载矢量模板的ostream与迭代器

[英]Overloading ostream of vector template with iterator

Why I can't use iterator in ostream overloading? 为什么我不能在ostream重载中使用迭代器?

If I use the same declaration using iterative approach it works. 如果我使用迭代方法使用相同的声明它是有效的。

Consider the following code: 请考虑以下代码:

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. Note that rhs is declared as reference to const , then rhs.v will be const too, then rhs.v.begin() will return a std::vector<U>::const_iterator , which can't be converted to std::vector<U>::iterator directly. 请注意, rhs被声明为对const引用,然后rhs.v也将是const ,然后rhs.v.begin()将返回一个std::vector<U>::const_iterator ,它不能转换为std::vector<U>::iterator直接。

  2. You should use typename for dependent type names . 您应该使用typename作为依赖类型名称

So change it to 所以改成它

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

BTW: void main() should be int main() . BTW: void main()应该是int main()

Try with 试试吧

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

If your rsh is const , you should use a const_iterator 如果你的rshconst ,你应该使用const_iterator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM