模板类&运算符重载

发布于 2025-01-03 20:54:37 字数 743 浏览 4 评论 0原文

我该如何重载如下所示的模板类?

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’

How do I go about overloading a template class like below?

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

I am getting errors like below:

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’

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱*していゐ 2025-01-10 20:54:37
template <class T>
typename List<T>::const_iterator& List<T>::const_iterator::operator++()

指定返回类型时,您并不在所谓的 List 词法范围内。由于封闭范围内没有类型 const_iterator ,因此您会收到错误(尽管该错误可能会表现得更好一点,恕我直言)。

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

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

但是,最好的想法是在类本身中内联定义这些内容。您对类外定义有什么特殊原因吗?

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

At the time the return type is specified, you're not inside the so-called lexical scope of List<T>. And since there is no type const_iterator in the enclosing scope, you get an error (though that one could manifest itself a little bit better, IMHO).

Another option for C++11 might be a trailing return type:

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

However, the best idea would be to just define these things inline in the class itself. Do you have a special reason for the out-of-class definitions?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文