【问题标题】:Overloading the << operator to print out a std::list重载 << 运算符以打印出 std::list
【发布时间】:2011-10-24 06:19:04
【问题描述】:

我在尝试实现一个重载的

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()的符号也不太自信。

如果有人能对这个问题有所了解,我将不胜感激。我正处于我盯着这个问题太久的地步!

【问题讨论】:

标签: c++ list iterator std


【解决方案1】:

curve 是 const 限定的,所以 curve.points 是 const 限定的,curve.points.begin() 返回一个 std::list&lt;Point&gt;::const_iterator,而不是 std::list&lt;Point&gt;::iterator

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

【讨论】:

  • 我不知道你是怎么回复的这么快,但你是完全正确的,这已经解决了我的问题。我想这突出了我对 std 库缺乏了解,但我会继续努力......谢谢!
【解决方案2】:

或者,

您可以将std::copy 用作:

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

确保operator&lt;&lt; 的签名是这样的:

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

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多