重载<<运算符以打印出std :: list

Rob*_*son 2 c++ iterator list std

我在尝试实现一个重载的<<运算符函数时遇到了一些问题,该函数可以打印出一个std :: list,它是我的一个类的成员.这个类看起来像这样:

class NURBScurve {
  vector<double> knotVector;
  int curveOrder;
  list<Point> points;
public:
  /* some member functions */
  friend ostream& operator<< (ostream& out, const NURBScurve& curve);
};
Run Code Online (Sandbox Code Playgroud)

我感兴趣的关键成员变量是"点"列表 - 这是我创建的另一个类,它存储点的坐标以及相关的成员函数.当我尝试将重载的<< operator函数实现为:

ostream& operator<<( ostream &out, const NURBScurve &curve)
{
 out << "Control points: " << endl;
 list<Point>::iterator it;
 for (it = curve.points.begin(); it != curve.points.end(); it++)
    out << *it; 
 out << endl;
 return out;
}
Run Code Online (Sandbox Code Playgroud)

我开始遇到问题.具体来说,我收到以下错误:错误:

no match for ‘operator=’ in ‘it = curve->NURBScurve::points. std::list<_Tp, _Alloc>::begin [with _Tp = Point, _Alloc = std::allocator<Point>]()’
/usr/include/c++/4.2.1/bits/stl_list.h:113: note: candidates are: std::_List_iterator<Point>& std::_List_iterator<Point>::operator=(const std::_List_iterator<Point>&)
Run Code Online (Sandbox Code Playgroud)

我在这里有点难过,但我相信它与我正在使用的列表迭代器有关.我对curve.points.begin()的表示法也不太自信.

如果有人能对这个问题有所了解,我会很感激.我已经盯着这个问题太久了!

Jam*_*lis 9

curve是const限定的,因此curve.points是const限定的并curve.points.begin()返回a std::list<Point>::const_iterator,而不是a std::list<Point>::iterator.

容器有两个begin()end()成员函数:一对不是const限定的成员函数并返回iterators,另一对是const限定的并返回const_iterators.这样,您可以迭代非const的容器并读取和修改其中的元素,但您也可以使用只读访问权限迭代const容器.


Naw*_*waz 6

要么,

你可以std::copy用作:

std::copy(points.begin(), points.end(), 
                      std::ostream_iterator<Point>(outStream, "\n"));
Run Code Online (Sandbox Code Playgroud)

确保签名operator<<是这样的:

std::ostream & operator <<(std::ostream &out, const Point &pt);
                                            //^^^^^ note this
Run Code Online (Sandbox Code Playgroud)