#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*
を使用しようとしました。私は、ポインタのためoperator++
とoperator*
をオーバーロードすることはできませんようにリストのイテレータとして `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)
が見えるコンパイルエラーを取得しています。
このオーバーロードを書籍Stroustrup: The C++ Programming Language (4th Edition) pg 703
からコピーしました。
誰でも私が間違ったことを説明できますか?
しかし、私は[OK]を、あなたは氏Stroustrup氏はそれを行ったかを説明することができます 'ノード*' – Ashot
の事前増分をオーバーロードしていますか?ここには本のリンクがあります。 https://www.dropbox.com/s/ipo5pkud6j4vr30/Straustrup4th.pdf?dl=0 – Ashot
@Ashot、この本では 'double ad [] = {1,2,3,4}; double s1 =累積(ad、ad + 4,0.0);double s2 = accumulate(ad、ad + 4,0); '。これらは完全に有効なイテレータです。 –