Objective:
Modify the set class so the arithmetic binary operators +, *, and -
are overloaded as member functions.
This set class implements a mathematical set of integers in the range 0..31.
Internally, it stores membership using a 32-bit machine word: each bit represents whether a value is in the set.
The masks array contains one bitmask per element position.
Your task is to implement three binary operators so that two set objects can be combined using natural
mathematical syntax:
s + t = unions * t = intersections - t = differenceStarter code:
#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;
}
Write member functions to overload:
+ operator so it defines a union of two set objects.
* operator so it defines an intersection of two set objects.
- operator so it defines the difference of two set objects.
Add the following prototypes to the class (note the right operand is passed as a parameter).
Use const correctness where appropriate.
class set {
...
set operator+(const set& v) const;
set operator*(const set& v) const;
set operator-(const set& v) const;
};
After you implement the operators, test your complete set ADT using the code below:
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 solution below and click Submit when you are ready.