C++ Class Construct  «Prev  Next»

Adding const member functions - Exercise

Objective: Add const print and intersection member functions to a class that implements a mathematical set.

Instructions

Use the class given below and write two external const member functions
  1. one to print all the elements of the set (pr_mems) and
  2. another to return the resulting set intersection (intersection).
The underlying representation of the set will be a 32-bit machine word.

The pr_mems function

This function should print out the integers that represent the bits in the set. For example, if set t has the value x0000 0000 0001 0101, then the integers represented in the set are 16, 4, and 1.

The set class


This code is also available in a file named set.cpp, which can be found in the compressed course download file available on the resources.

#include <iostream.h>

// Implementation of an ADT for type set.
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:
   void init (unsigned long int i = 0){
		t = i; 
	}
   bool  in(unsigned long int i) const
      { return bool( (t & masks[i]) != 0); }
   void  pr_mems() const;
   set  sunion(const set& v) const;
   set  intersection(const set& v) const;
   private:
   unsigned long int  t;
};

set  set::sunion(const set& v) const{
   set temp;
   temp.init ((t | v.t));
   return temp;
}

int main(){
   set   s, t, w;

   s.init(0x555);
   t.init(0x10303021);
   w.init();

   cout << " set s = " ;
   s.pr_mems() ;
   cout << " set t = " ;
   t.pr_mems();

   w = t.sunion(s);
   cout << "\nunion: ";
   w.pr_mems();
   w = t.intersection(s);
   cout << "\nintersection: ";
   w.pr_mems();
}

Paste the source code below and click the Submit button when you are ready to submit this exercise.