簡體   English   中英

重載矢量模板的ostream與迭代器

[英]Overloading ostream of vector template with iterator

為什么我不能在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. 請注意, rhs被聲明為對const引用,然后rhs.v也將是const ,然后rhs.v.begin()將返回一個std::vector<U>::const_iterator ,它不能轉換為std::vector<U>::iterator直接。

  2. 您應該使用typename作為依賴類型名稱

所以改成它

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

BTW: void main()應該是int main()

試試吧

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

如果你的rshconst ,你應該使用const_iterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM