20-CS-122-001 Computer Science II Spring 2012
Singly Linked List With Class List

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

Prev      Next      Lectures      Makefile      uselist.4.cc      list.4.h      list.4.cc      power point

#include <iostream>
#include "list.4.h"
using namespace std;

// Overload all the operators for nice looking output
class B {
   int number;

   long long fact (int n) {
      if (n == 1) return 1;
      return n * fact(n-1);
   }

public:
   B (int number) { this->number = number;  }
   int get_number () { return number; }
   long long factorial () { return fact(number); }
};

void display_B_object (void *obj) {  
   cout << ((B*)obj)->get_number() 
	<< "! = " << ((B*)obj)->factorial();  
}

bool find_B_object (void *obj, void *what) {
   return ((B*)obj)->get_number() == *(int*)what;
}

ostream & operator<<(ostream &out, B &b) {
   out << b.get_number() << " ";
   return out;
}

int main () {
   List l;
   l = l + new B(6) + new B(7) + new B(8) + new B(9) + new B(10);
   l += new B(11);
   l += find_B_object;
   l += display_B_object;
   cout << "First:\n  " << l << "\nAgain:\n  " << l;
   cout << "Removed 8:\n  " << (l = l - new int(8));
   cout << "With 7, 10 removed:\n  " << l - new int(10) - new int(7);
   l -= new int(6);
   cout << "Removed 6:\n  " << l;
   l += new B(12);
   cout << "Added 12:\n  " << l;
}