#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/