Professional Documents
Culture Documents
OOP - Transperencies CH 03
OOP - Transperencies CH 03
Operator Overloading
#include<iostream.h>
class Space
{
int x,y;
public:
void get(int a, int b)
{
x = a;
y = b;
}
void show()
{
cout<<"\n X = "<<x;
cout<<"\n Y = "<<y;
}
void operator–()
{
x = –x;
y = –y;
}
};
int main()
{
Space s;
s.get(10,52);
cout<<"\nBefore overloading:";
s.show();
cout<<"\nAfter overloading:";
–s;
s.show();
return(0);
}
#include<iostream.h>
class Index
{
int val;
public:
Index(){}
Index(int z)
{
val = z;
}
void show()
{
cout<<"\n val = "<<val;
}
void operator++()
{
val = val + 10;
}
};
int main()
{
Index sit(9);
cout<<"\nBefore overloading:";
sit.show();
cout<<"\nAfter overloading:";
++sit;
sit.show();
return(0);
}
class Overload
{
int n1,n2,n3;
public:
Overload(){}
Overload(int a,int b,int c)
{
n1 = a; n2 = b; n3 = c;
}
void show()
{
cout<<"\n n1 = "<<n1;
cout<<"\n n2 = "<<n2;
cout<<"\n n3 = "<<n3;
}
v o i d o p e r a t o r *()
{
n1 = n2 = n3 = 0;
}
};
int main()
{
Overload check(6,3,4);
cout<<"\nBefore overloading:";
check.show();
cout<<"\nAfter overloading:";
*check;
check.show();
return(0);
}
class Complex
{
float x,y,z;
public:
Complex( ) { }
Complex(float a, float b, float c)
{
x=a; y=b; z=c;
}
void display(char *s)
{
cout<<"\n"<<s;
cout<<"\n X:"<<x;
cout<<"\n Y:"<<y;
cout<<"\n Z:"<<z;
}
Complex operator + (Complex);
};
Complex Complex :: operator+(Complex m)
{
Complex temp;
temp.x = x + m.x;
temp.y = y + m.y;
temp.z = z + m.z;
return(temp);
}
int main( )
{
Complex rate1(45.3, 56.8, 12.02);
Complex rate2(6.08, 19.9, 75.75);
Complex rate3 = rate1 + rate2;
rate1.display("\nFirst");
rate2.display("\nSecond");
rate3.display("\nAddition");
return(0);
}
class Vector
{
int a[10];
public:
Vector(){ }
void inPut()
{
cout<<"Enter 10 values : ";
for(int i=0;i<10;i++)
cin>>a[i];
}
void outPut()
{
cout<<"\nResultant array : ";
for(int i=0;i<10;i++)
cout<<"\n"<<a[i];
}
friend Vector operator* (Vector x,int y);
};
Vector operator*(Vector x, int y)
{
Vector temp;
for(int i=0;i<10;i++)
temp.a[i] = x.a[i] * y;
return(temp);
}
int main( )
{
clrscr( );
Vector v;
v.inPut( );
v = v * 5;
v.outPut( );
return(0);
}