Operator Overloading  «Prev 

Overloading Binary Operators - Exercise

Objective:Modify the set class so the arithmetic binary operators +, -, and * are overloaded.

The set class

The set class implements a mathematical set, similar to the built-in set type in Pascal. The underlying representation of the set will be a 32-bit machine word. If you took Building Classes in C++, you have already modified a set class similar to the one below.
#include <iostream.h>

const unsigned long int masks[32] = {
   0x80000000, 0x40000000, 0x20000000, 0x10000000,
   0x8000000, 0x4000000, 0x2000000, 0x1000000,
   0x800000, 0x400000, 0x200000, 0x100000,
   0x80000, 0x40000, 0x20000, 0x10000,
   0x8000, 0x4000, 0x2000, 0x1000,
   0x800, 0x400, 0x200, 0x100,
   0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1};

class set {
public:
   set(unsigned long int i) { t = i; }
   set() { t = 0x0; }
   void  u_add(int i) { t |= masks[i]; }
   void  u_sub(int i) { t  &= ~masks[i]; }
   bool  in(int i) const
     { return ( (t & masks[i]) != 0); }
   void  pr_mems() const;
   set  set_union(const set& v) const
     { return (set(t | v.t)); }

private:
   unsigned long int  t;
};

void  set::pr_mems() const
{
   cout << "\n set members: { ";
   for (int i =0; i < 32; i++)
      if (in(i))
         cout << i << ' '; 
   cout << '}' << endl;
}
Exercise Instructions
Write member functions that overload
  1. the binary + operator so it defines a union of two set objects
  2. the binary * operator so it defines an intersection of two set objects
  3. the binary - operator so it defines the difference of two set objects

class set {
   .....
   set operator+(set& v);
   set operator*(set& v);
   set operator-(set& v);
};

Test your complete set ADT using the following code:
int main()
{
   set  s(0x5555), t(0x10303021), w, x;
   s.pr_mems(); t.pr_mems();
   w.pr_mems(); x.pr_mems();
   w = s + t;             //set union
   x = s * t;             //set intersection
   t = t - s;             //set difference
   s.pr_mems(); t.pr_mems();
   w.pr_mems(); x.pr_mems();
}

The above code is also available in the file named set.cpp.
Paste your code below and click the Submit button when you are ready to submit this exercise.