DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

OperatorOverload.cpp

02.01.2008
| 886 views |
  • submit to reddit
        #include <iostream>

using namespace std;

class set
{
 public:
        set();
        set(int n, char *members);
        set operator + (set b);
        set operator * (set b);
        friend ostream& operator << (ostream& os, set a);
 private:
   int n;
   char *members;
};

set::set()
{
 this->n = 0;
}

set::set(int n, char *members)
{
 this->n = n;
 this->members = members;
}

set set::operator + (set b)
{
 int i,j,k;
 int cn;
 bool rep;
 int an = this->n;
 int bn = b.n;
 char *amembers = this->members;
 char *bmembers = b.members;

 cn = an+bn;
 for (j=0; j<bn; j++)
 {
  rep = false;
  for (i=0; i<an; i++)
    if (amembers[i] == bmembers[j])
      rep = true;
  if (rep) cn--;                // decrement count if repetition
 }

 char *cmembers = new char[cn];
 for (k=0; k<an; k++)
   cmembers[k] = amembers[k];

 for (j=0; j<bn; j++)
 {
  rep = false;
  for (i=0; i<an; i++)
    if (amembers[i] == bmembers[j])
      rep = true;
  if (!rep) cmembers[k++] = bmembers[j];
 }    

 set c(cn, cmembers);
 return (c);
}

set set::operator * (set b)
{
 int i,j,k;
 int cn;
 bool rep;
 int an = this->n;
 int bn = b.n;
 char *amembers = this->members;
 char *bmembers = b.members;

 cn = 0;
 for (j=0; j<bn; j++)
 {
  rep = false;
  for (i=0; i<an; i++)
    if (amembers[i] == bmembers[j])
      rep = true;
  if (rep) cn++;                // increment count if common
 }

 char *cmembers = new char[cn];

 k = 0;
 for (j=0; j<bn; j++)
 {
  rep = false;
  for (i=0; i<an; i++)
    if (amembers[i] == bmembers[j])
      rep = true;
  if (rep) cmembers[k++] = bmembers[j];
 }    

 set c(cn, cmembers);
 return (c);
}

ostream& operator << (ostream& os, set a)
{
 int i;
 os << "{";
 for (i=0; i<a.n; i++)
   if (i != a.n-1)
     os << a.members[i] << ", ";
   else
     os << a.members[i];
 os << "}";
 return (os);
}

main()
{
 set x(4,"abcd"), y(4,"bcde"), z, w;
 
 // Test our Overloaded (+) Operator on the two SETS (x,y)
 z = x + y;
 
 // Test our Overloaded (+) Operator on the two SETS (x,y)
 w = x * y;
 
 cout << endl;
 cout << "[ ] The SET {x} is = " << x << endl;
 cout << "[ ] The SET {y} is = " << y << endl;
 cout << endl;
 cout << "[+] When Added (x+y), the sum {z} BECOMES = " << z << endl;
 cout << "[*] When Multiplied the resulting set {w} = " << w << endl;
 
 getchar();
 
}