2017-01-05 51 views
0
#include <iostream> 
using namespace std; 
class Stack 
{ 
    int items[10]; 
    int sp; 
    public: 
    friend class StackIter; 
    Stack() 
    { 
     sp = - 1; 
    } 
    void push(int in) 
    { 
     items[++sp] = in; 
    } 
    int pop() 
    { 
     return items[sp--]; 
    } 
    bool isEmpty() 
    { 
     return (sp == - 1); 
    } 
    StackIter *createIterator() const // 2. Add a createIterator() member 

}; 

class StackIter 
{ 
    // 1. Design an "iterator" class 
    const Stack *stk; 
    int index; 
    public: 
    StackIter(const Stack *s) 
    { 
     stk = s; 
    } 
    void first() 
    { 
     index = 0; 
    } 
    void next() 
    { 
     index++; 
    } 
    bool isDone() 
    { 
     return index == stk->sp + 1; 
    } 
    int currentItem() 
    { 
     return stk->items[index]; 
    } 
}; 

StackIter *Stack::createIterator() const 
{ 
    return new StackIter(this); 
} 

bool operator == (const Stack &l, const Stack &r) 
{ 
    // 3. Clients ask the container object to create an iterator object 
    StackIter *itl = l.createIterator(); 
    StackIter *itr = r.createIterator(); 
    // 4. Clients use the first(), isDone(), next(), and currentItem() protocol 
    for (itl->first(), itr->first(); !itl->isDone(); itl->next(), itr->next()) 
    if (itl->currentItem() != itr->currentItem()) 
     break; 
    bool ans = itl->isDone() && itr->isDone(); 
    delete itl; 
    delete itr; 
    return ans; 
} 

int main() 
{ 
    Stack s1; 
    for (int i = 1; i < 5; i++) 
    s1.push(i); 
    Stack s2(s1), s3(s1), s4(s1), s5(s1); 
    s3.pop(); 
    s5.pop(); 
    s4.push(2); 
    s5.push(9); 
    cout << "1 == 2 is " << (s1 == s2) << endl; 
    cout << "1 == 3 is " << (s1 == s3) << endl; 
    cout << "1 == 4 is " << (s1 == s4) << endl; 
    cout << "1 == 5 is " << (s1 == s5) << endl; 
} 

編譯錯誤:Iterator模式例如在C++給錯誤

main.cpp:25:5: error: 'StackIter' does not name a type 
    StackIter *createIterator()const // 2. Add a createIterator() member 
main.cpp: In function 'bool operator==(const Stack&, const Stack&)': 
main.cpp:68:22: error: 'const class Stack' has no member named 'createIterator' 
    StackIter *itl = l.createIterator(); 
main.cpp:69:22: error: 'const class Stack' has no member named 'createIterator' 
    StackIter *itr = r.createIterator(); 

我在做什麼錯?

+0

在'class Stack'之前轉發declare'class StackIter;' – sameerkn

+0

@sameerkn,這不會幫助,因爲他在實際定義之前嘗試使用不完整類型 – Tejendra

+0

在'StackIter * '堆棧'的類定義中的createIterator()const' – mike510a

回答

1

「StackIter * createIterator()const」後面缺少分號。我添加了一個分號。然後該程序運行。沒有錯誤。

+0

即使在添加分號後仍留有分號我收到錯誤。 –