【发布时间】: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