2011-08-10 68 views
2

我一直有一些问题,试图实现一个超载的< <运算符函数,可以打印出一个std :: list是我的一个类的成员。这个类看起来是这样的:重载<<运算符打印出一个std :: list

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

的关键成员变量我感兴趣的是“点”的名单 - 这是我创建了存储与相关联的成员函数沿的点的坐标另一个类。当我尝试并实现重载< <操作功能:

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; 
} 

我开始得到的问题。具体来说,我得到以下错误: 错误:

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>&) 

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

如果任何人都可以解决这个问题,我将不胜感激。我一直在盯着这个问题太久了!

+0

你能给[漂亮的打印](HTTP:/ /stackoverflow.com/questions/4850473/pretty-print-c-stl-containers)试一试:-) –

回答

9

curve是const限定的,所以curve.points是const限定和curve.points.begin()返回std::list<Point>::const_iterator,而不是一个std::list<Point>::iterator

容器具有两个begin()end()成员函数:一对不是常量限定成员函数和返回iterator s时,另一对是常量限定,并返回const_iterator秒。通过这种方式,您可以遍历不是const的容器,并且可以读取和修改其中的元素,但是您也可以通过只读访问遍历const容器。

+0

我不知道你是如何回答的,但你完全正确,而且这个答案是fi xed我的问题。我想这已经强调了我对标准库的理解不够,但我会继续努力......谢谢! –

6

或者,

您可以使用std::copy为:

std::copy(points.begin(), points.end(), 
         std::ostream_iterator<Point>(outStream, "\n")); 

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

std::ostream & operator <<(std::ostream &out, const Point &pt); 
              //^^^^^ note this