2016-07-12 1 views
4
#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*을 사용하려고 시도했습니다. 나는 컴파일러 오류를 얻고있다목록의 반복자로 'Node *'사용하기

내가 포인터에 대한 operator++operator*를 오버로드 할 수처럼
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에서이 오버로드를 복사했습니다.

누구든지 내가 잘못 한 것을 설명 할 수 있습니까?

답변

3

std::accumulate의 입력은 InputIterator의 요구 사항을 충족해야합니다.

InputIterator의 요구 사항 중 하나는 사전 증가 연산자를 지원한다는 것입니다.

Node*에서 선 증가 연산자를 사용할 수 있지만 내장 논리를 사용하여 포인터를 증가시킵니다. 인수의 유형 Node* 때문에

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

가 잘못되었습니다. Nodeoperator++을 오버로드 할 수 있지만 Node*을 오버로드 할 수 없습니다. 는 C++ 11 표준 (강조 내)에서

:

13.5 오버 연산자

6 조작자 활동한다 어느 비 정적 멤버 함수이거나 될 비회원 함수 및 에는 형식이 클래스, 클래스에 대한 참조, 열거 또는 열거 형에 대한 참조 인 하나 이상의 매개 변수가 있습니다.

+0

하지만'노드 *'에 대한 선행 증가를 오버로드는 – Ashot

+1

좋아, 당신은 설명 할 수 씨 스트로브 스트 룹은 일을 어떻게? 여기에 그 책에 대한 링크가 있습니다. https://www.dropbox.com/s/ipo5pkud6j4vr30/Straustrup4th.pdf?dl=0 – Ashot

+0

@Ashot,이 책은'double ad [] = {1,2,3,4}; double s1 = 누적 (ad, ad + 4,0.0); double s2 = accumulate (ad, ad + 4,0);'. 그것들은 완벽하게 유효한 반복자입니다. –

0

프리미티브 형식이나 점에 대해 연산자를 오버로드 할 수 없습니다. 따라서 Node에 대한 반복기를 작성해야합니다.

class iterator { 
public: 
    iterator(Node *node): _node(node) {} 
    iterator operator++() { 
    _node = _node->next; 
    return *this; 
    } 
    iterator operator++(int) { 
    iterator tmp = *this; 
    ++(*this); 
    return tmp; 
    } 
    bool operator == (const iterator &iter) const { 
    return _node == iter._node; 
    } 
    int operator*() { 
    return _node->value; 
    } 
private: 
    Node *_node; 
}; 
관련 문제