【问题标题】:Overloading ostream of vector template with iterator用迭代器重载向量模板的ostream
【发布时间】:2017-07-04 08:32:36
【问题描述】:

为什么我不能在 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;
}

【问题讨论】:

  • 如果 C++11 可用于您的目标平台,您可能希望将迭代器的类型声明为 auto,以便编译器可以为您推断出正确的类型。打字要容易得多,无论是从哪个意义上来说。

标签: c++ templates operator-overloading ostream


【解决方案1】:
  1. 注意rhs被声明为对const的引用,那么rhs.v也将是const,那么rhs.v.begin()将返回一个std::vector&lt;U&gt;::const_iterator,它不能被转换为@ 987654329@直接。

  2. 您应该将typename 用于dependent type names

所以改成

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

顺便说一句:void main() 应该是 int main()

【讨论】:

    【解决方案2】:

    试试

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

    如果你的rshconst,你应该使用const_iterator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多