20-CS-122-001 Computer Science II Spring 2012
List class, Many Operators Overloaded

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

Prev      Next      Lectures      list.0_1.h      list.0_1.cc

#include <iostream>
#include "list.0_1.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;
}

List &operator+(B *obj, List &lst) {
   lst.add(obj);
   return lst;
}

int main () {
   List 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: " << l << "Again: " << l;
   cout << "Removed 8:\t" << l - new int(8);
   cout << "Removed 7, 10:\t" << l - new int(10) - new int(7);
   l -= new int(6);
   cout << "Removed 6:\t" << l;
   l += new B(12);
   cout << "Added 12:\t" << l;
}