20-CS-122-001 Computer Science II Spring 2012
Simple List - Overload List Operators

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      Source

#include <iostream>
using namespace std;

// Overload the "<<", "+=" and "-=" for the List class
class A {
   friend class List;  // Must make List class a friend so it can access next
   friend ostream & operator<<(ostream &, List &); // Again must know List
   friend ostream & operator<<(ostream &, A *);
   int number;
   A *next;            // Why should we have a "next"?
                       // What'f there is a different kind of List to put A in?
public:
   A (int number) { this->number = number; next = NULL; }
};

ostream & operator<<(ostream &out, A *a) {
   out << a->number;
   return out;
}

class List {
   friend ostream & operator<<(ostream &, List &);
   A *head;

public:
   List () { head = NULL; }
   
   void operator+=(A *obj) {  obj->next = head;   head = obj;  }
   
   void operator-=(int number) {
      if (head->number == number) {
	 head = head->next;
	 return;
      }
      for (A *ptr=head ; ptr->next != NULL ; ptr=ptr->next) {
	 if (ptr->next->number == number) {
	    ptr->next = ptr->next->next;
	    return;
	 }
      }
   }
};

ostream &operator<<(ostream &out, List &lst) {
   for (A *ptr = lst.head ; ptr != NULL ; ptr=ptr->next) 
      out << ptr->number << " ";
   return out;
}

int main () {
   List lst;
   lst += new A(23);
   lst += new A(42);
   lst += new A(16);
   lst += new A(67);
   cout << lst << "\n";
   lst -= 16;
   cout << lst << "\n";
   lst += new A(16);
   cout << lst << "\n";
}