Operator overloading is an important technique in C++ programming language. This CPP program example is for SET operations. It is a simple example source code for students and beginners.
- SEE: Swap program in C++
Set operations in C++:
Few of the set operators in C++ programming are,
- SET - Union,
- SET - Intersection,
- SET - Subtraction,
- & SET - Exclusive OR,
Related: C program Examples & Explanation
In this C++ operator overloading program we are using SET operators for the further process. There are few functions and a class for an operator overloading process. Few methods are,
- input() - Function is for getting an Input values,
- sort() - Method is for sorting operation,
- display() - Method is for output display.
- Read: Call by reference programs
Read: Learn English Quickly
Worth Read: C++ Interview Questions
SET Operations Program:
Write an example C++ source code for operator overloading using SET operators.
#include<iostream.h> #include<conio.h> class OprtnOfSet { int k[15],N; public: OprtnOfSet() //Constructor without an argument {} OprtnOfSet(int a) //Constructor with an argument { this->a=a; } void input(); void sort(); void display(); void operator +(OprtnOfSet); void operator -(OprtnOfSet); void operator <(OprtnOfSet); // Super SET operation void operator >(OprtnOfSet); // Sub SET operation }; void OprtnOfSet :: operator <(OprtnOfSet os2) { OprtnOfSet os3; } void Set::input() { cout<<"\n Give inputs of the Set : "; for(int a=0;a<N;a++) cin>>k[a]; sort(); } void Set ::sort() { for(int r=0;r<N-1;r++) for(int m=r+1;m<N;m++) if(k[r]>k[m]) { int x=k[r]; a[r]=k[m]; k[m]=x; } } void OprtnOfSet::display() { for(int r=0;r<N;r++,cout<<"\n") cout<<k[r]; } void OprtnOfSet::operator +(OprtnOfSet os2) { OprtnOfSet os3; int r=0,m=0,s; for(k=0;r<N && m<os2.N;k++) { if(k[r]==os2.k[m]) { os3.k[s]=k[r++]; m++; } else if(k[r]<os2.k[m]) os3.k[s]=k[r++]; else os3.k[s]=k[m++]; } while(r<N) os3.k[s++]=k[r++]; while(j<so2.N) os3.k[s++]=os2.k[m++]; cout<<"\n\t A union B\n\t"; os3.N=s; os3.display(); } void OprtnOfSet :: operator -(OprtnOfSet os2) { OprtnOfSet os3; int r=0,m=0,s; for(s=0;r<N && m<os2.N;) { if(k[r]==os2.k[m]) { os3.k[s++]=k[r]; m++; r++; } if(k[r]<os2.k[m]) m++; else r++; } cout<<"\n\t A Intersection operation B \n\t"; os3.N=s; os3.display(); } void main() { clrscr(); int v,v1; cout<<"\n CPP Set Operations Program\n"; cout<<"Give input no.of values to SET A&B:"; cin>>v>>v1; Set os1(v),os2(v1),os3; os1.input(); os2.input(); clrscr(); cout<<"\n SET A Values \n"; os1.display(); cout<<"SET B Values\n"; os2.display(); os1+os2; //SET Union operation os1-os2; //SET Intersection operation getch(); }