Description: This program shows how to overload binary operators [such as +,-,* and /]. The program uses switch case constructor to present menu.
Code:
//Compiling Tool: Code::Block IDE with MinGW
//Program shows how to overload binary opertor
#include<iostream>
#include<conio.h> //for getch()
#include<process.h>
//#include<math.h> //for sqrt()
#include<cstdlib> //for system()
using namespace std;
class demo
{
float
a,b;
public:
void getdata();
void display();
demo
operator +(demo);
demo
operator -(demo);
demo
operator *(demo);
demo
operator /(demo);
int
operator ==(demo);
};
void demo::getdata()
{
cout<<"Enter values of a and b:";
cin>>a>>b;
}
void demo::display()
{
cout<<"a="<<a<<"\t b="<<b;
}
demo demo::operator +(demo d1)
{
demo
d2;
d2.a=a+d1.a;
d2.b=b+d1.b;
return d2;
}
demo demo::operator -(demo d1)
{
demo
d2;
d2.a=a-d1.a;
d2.b=b-d1.b;
return d2;
}
demo demo::operator *(demo d1)
{
demo
d2;
d2.a=a*d1.a;
d2.b=b*d1.b;
return d2;
}
demo demo::operator /(demo d1)
{
demo
d2;
d2.a=a/d1.a;
d2.b=b/d1.b;
return d2;
}
int demo::operator ==(demo d1)
{
if((a==d1.a)&&(b==d1.b))
return
1;
else
return
0;
}
int main()
{
int ch;
demo d1,d2,d3;
top:
system("Cls");
cout << endl;
cout<<"***Operator Overloading Program***"<< endl;
cout<<" 1. Addition"<< endl;
cout<<" 2. Subtraction"<< endl;
cout<<" 3. Multiplication"<< endl;
cout<<" 4. Division"<< endl;
cout<<" 5. Comparison"<< endl;
cout<<" 6. Quit"<< endl;
cout<<"Enter your Choice:_";
cin>>ch;
if(ch<6)
{
cout<<"First Object:\n";
d1.getdata();
cout<<"Second Object:\n";
d2.getdata();
}
switch(ch)
{
case 1:
d3=d1+d2;
cout<<"Third Object:\n";
d3.display();
break;
case 2:
d3=d1-d2;
cout<<"Third Object:\n";
d3.display();
break;
case 3:
d3=d1*d2;
cout<<"Third Object:\n";
d3.display();
break;
case 4:
d3=d1/d2;
cout<<"Third Object:\n";
d3.display();
break;
case 5:
if(d1==d2)
cout<<"Objects are Equal";
else
cout<<"Objects are Not Equal";
break;
case 6:
exit(0);
break;
default:
cout<<"Wrong Choice!!!Press any key to exit";
}
getch();
goto top;
}
Output:
If you want to write or construct or program C++ mini-project and do not know how or from where to start buy this simple e-book: Code Review of 26 C++ mini-projects. For book sample click this link.
Add your comments in below available comment box.
Note: Click these label/tags to view all related posts. Tags: C++Code
…till next post, bye-bye & take care.
No comments:
Post a Comment