c++ - 使用 `Node*` 作为列表的迭代器

标签 c++ list c++11 iterator

#include <iostream>
#include <algorithm>

struct Node
{
    int value_;
    Node* next_;

    Node(int value, Node* next = nullptr)
        : value_(value)
        , next_(next)
    {}
};

Node* operator++(Node* node)
{
    node = node->next_;
    return node;
}

int operator*(Node* node)
{
    return node->value_;
}

int main()
{
    Node* first = new Node(10);
    first->next_ = new Node(20);
    first->next_->next_ = new Node(17);

    Node* endIter = nullptr;

    std::cout << std::accumulate(first, endIter, 0) << std::endl;
}

在这个例子中,我尝试使用 Node* 作为列表的迭代器。我收到编译器错误

  1 main.cpp:15:28: error: Node* operator++(Node*) must have an argument of class or enumerated type
  2  Node* operator++(Node* node)
  3                             ^
  4 main.cpp:21:25: error: int operator*(Node*) must have an argument of class or enumerated type
  5  int operator*(Node* node)

看起来我无法为指针重载 operator++operator*

我从 Stroustrup: The C++ Programming Language (4th Edition) pg 703 一书中复制了这个重载。

谁能解释一下我做错了什么?

最佳答案

std::accumulate 的输入必须满足 InputIterator 的要求.

InputIterator 的要求之一是它支持预递增运算符。

您可以在 Node* 上使用预递增运算符,但它将使用内置逻辑来递增指针。

Node* operator++(Node* node) { ... }

无效,因为参数的类型是 Node*。您可以为 Node 重载 operator++ 但不能为 Node* 重载。

来自 C++11 标准(强调我的):

13.5 Overloaded operators

6 An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

关于c++ - 使用 `Node*` 作为列表的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38320365/

相关文章:

c# - 从 Razor 页面发送 List<Object> 到 Update 的行?

c++11 - 如何使用 cmake 测试我的库中的 static_assert?

c++ - 在成员函数中访问参数的类成员

c++ - unique_ptr::get() 而不是 &* 有什么用?

java - 如何将类的目标文件与源文件链接

c - C 中的双向链表

c++ - 如何提供用于创建静态和动态大小 vector 的通用接口(interface)?

python - 在python中,有没有办法自动替换缺失值?

c++ - 循环计算矩形的面积公式

c++ - 是否可以在 C++11 中编写宏 existenceof(S,f) 或 hasfield(S,f)?