运营商=申报问题

时间:2013-10-16 07:01:26

标签: c++ operators return-type

我为一个类似的值分配一个奇怪的问题感到难过。这是给我问题的代码:

1. ListIterator<int> itr = lst.begin();
2.itr++;
3.itr = lst.begin();

所以第1行和第2行工作正常;但是,当我在声明之后尝试制作itr = lst.begin()时,我收到以下错误:

ListMain.cpp:46: error: no match for ‘operator=’ in ‘itr = lst. List<T>::begin [with T =      int]()’
List.h:183: note: candidates are: void ListIterator<T>::operator=(ListIterator<T>&)   [with T = int]

现在我的operator =目前是:

void operator = (iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

因为我的begin()函数返回一个ListIterator,这不应该只是重新分配列表迭代器还是我错过了什么?

非常感谢对此问题的任何见解。

1 个答案:

答案 0 :(得分:2)

您的operator=通过非const引用获取其参数。因此,临时(例如begin()返回的对象)不能绑定它。如果您需要自定义复制赋值运算符,请将其更改为:

void operator = (const iterator & rhs) {theList = rhs.theList; currentLink = rhs.currentLink;}

此外,为了使操作符符合标准库要求,您应该更改它以返回对所分配对象的引用:

iterator& operator = (const iterator & rhs) {
  theList = rhs.theList;
  currentLink = rhs.currentLink;
  return *this;
}

最后,你需要一个自定义赋值运算符吗?你所做的只是成员的分配。如果它们都是成员,那么最好完全删除运算符并依赖编译器生成的运算符。

相关问题