Popular Posts

6/24/2012

Sample Operator_Overloading in C++

Let see the following code :
====================

#include<iostream.h>
#include<math.h>
class Rectangle{
private:
float l,w;
public:
Rectangle(float l1,float w1):l(l1),w(w1){}
void output();
float area(){return (l*w);}
Rectangle operator=(float s);
Rectangle operator+(Rectangle p);
float operator-(Rectangle p);
int operator>(Rectangle p);
int operator==(Rectangle p);
float operator*();
float operator!();
};
void Rectangle::output(){
cout<<l<<"\t"<<w<<"\t"<<area()<<endl;
}

Rectangle Rectangle::operator=(float s){
w=sqrt(s/2);
l=2*w;
return *this;

//Or other ways that use return Constructor
/*float w1,l1;
w1=sqrt(s/2);
l1=2*w1;
return Rectangle(l1,w1);*/
}

Rectangle Rectangle::operator+(Rectangle p){
//you want to get new object
  float w1,l1;
l1=l+p.l; //l & w refer to own object and "p." refer to other object
w1=w+p.w;
return Rectangle(l1,w1);

//You want ot Update the same object
/* l=l+p.l;
w=w+p.w;
return *this;*/
}

float Rectangle::operator-(Rectangle p){
return fabs(area()-p.area());
}
int Rectangle::operator>(Rectangle p){
return (area()>p.area());
}
int Rectangle::operator==(Rectangle p){
return (area()==p.area());
}
float Rectangle::operator*(){ return area();}
float Rectangle::operator!(){
float d;
d=sqrt(l*l+w*w);
return d;
}
void main(){
Rectangle P1(5.6,3.2),P2(5.2,3.0),P3(9.2,7.0);
cout<<"Length\tWidth\tArea\n";
P1.output();
P2.output();
P3.output();

cout<<"\n\nUse Operator Funtion\n";
P1=72.0; P1.output();
P3=P1+P2; P3.output(); //or (P1+P2).output();
//show the sam object P1.output();

float s1,s2,s3;
s1=P1-P2; cout<<"S1:"<<s1<<endl;
s2=*P1; cout<<"\nArea of P1:\t"<<s2<<endl;
s3=!P1; cout<<"\nDiagonal of P1:\t"<<s3<<endl;
if(P1>P2) cout<<"\nArea of P1>P2"<<endl;
else if (P1==P2) cout<<"\nArea of P1=P2"<<endl;
else cout<<"\nArea of p1<p2"<<endl;
}
//Leave us a command and share it to ur friends ..!

0 comments:

Post a Comment