模板类&运算符重载

时间:2012-02-07 03:15:42

标签: c++ templates pass-by-reference class-template

如何重载模板类,如下所示?

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 ‘&’ token
List.cpp:23: error: expected constructor, destructor, or type conversion before ‘List’
List.cpp:30: error: expected constructor, destructor, or type conversion before ‘&’ token
List.cpp:35: error: expected constructor, destructor, or type conversion before ‘List’

1 个答案:

答案 0 :(得分: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&
{
  // ...
}

但是,最好的想法是在类本身中内联定义这些内容。您是否有特殊原因来进行课外定义?