Note: this example uses a common technique for implementing an iterator in Java and translates it to C++ for the purposes of demonstrating how the friend modifier works.
#ifndef SORTEDLIST_H #define SORTEDLIST_H #include "Student.h" class SortedList { friend class Iterator; public: SortedList(); bool insert(Student *s); Student *find(int studentID); Student *remove(int studentID); void print() const; private: struct ListNode { Student *student; ListNode *next; }; ListNode *head; // pointer to first node in the list }; #endif
#ifndef ITERATOR_H #define ITERATOR_H #include "Student.h" #include "SortedList.h" class Iterator { public: Iterator(const SortedList &list); Student *next(); bool hasNext(); private: SortedList::ListNode *curr; }; #endif
#include "Iterator.h" using namespace std; Iterator::Iterator(const SortedList &list) : curr(list.head) { } Student *Iterator::next() { if (!hasNext()) return 0; Student *temp = curr->student; curr = curr->next; return temp; } bool Iterator::hasNext() { return curr != 0; }
SortedList L1; for (int i = 0; i < 10; i++) L1.insert(new Student(i)); Iterator iter(L1); while (iter.hasNext()) { Student *student = iter.next(); cout << student->getID() << " "; } cout << endl;