2

如何重载如下模板类?

template <class T>
const_iterator& List<T>::const_iterator::operator++()
{
  current = current->next;
  return *this;
}

template <class T>
const_iterator List<T>::const_iterator::operator++(int)
{
  const_iterator old = *this;
  ++( *this );
  return old;
}

我收到如下错误:

List.cpp:17: error: expected constructor, destructor, or type conversion before ‘&amp;’ token
List.cpp:23: error: expected constructor, destructor, or type conversion before ‘List’
List.cpp:30: error: expected constructor, destructor, or type conversion before ‘&amp;’ token
List.cpp:35: error: expected constructor, destructor, or type conversion before ‘List’
4

1 回答 1

3
template <class T>
typename List<T>::const_iterator& List<T>::const_iterator::operator++()

在指定返回类型时,您不在List<T>. 而且由于封闭范围内没有类型const_iterator,因此您会收到一个错误(尽管该错误可能会更好地表现出来,恕我直言)。

C++11 的另一个选项可能是尾随返回类型:

template<class T>
auto List<T>::const_iterator::operator++()
    -> const_iterator&
{
  // ...
}

然而,最好的办法是在类本身内联定义这些东西。您对课外定义有特殊原因吗?

于 2012-02-07T03:19:34.447 回答