Tuesday, 27 November 2012

operator overloading


#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class space
{
public:
int x;
int y;
int z;
space(int a, int b,int c)
{x=a;y=b;z=c;}
void operator --()
{
x=x-1;
y=y-1;
z=z-1;
}
void operator ++()
{
x=x+1;
y=y+1;
z=z+1;
}
void display()
{
cout<<"x: "<<x;
cout<<"\ny: "<<y;
cout<<"\nz: "<<z;
cout<<"\n\n";
}
};

class str
{
public:
char *p;
str()
{}
str(char *tem)
{
p = new char[strlen(tem)+1] ;
strcpy(p,tem);
}
str operator + (str &s)
{
char *temp;
temp= new char[strlen(p) + strlen(s.p)+1];
temp = strcat(p,s.p);
return str(temp);
}
};
int main()
{
space c(10,20,30);
cout<<"Before:\n";
c.display();
c--;
cout<<"After --:\n";
c.display();
space d(1,2,3);
cout<<"Before:\n";
d.display();
d++;
cout<<"After ++:\n";
d.display();

cout<<"\n\nFor binary operator-> ";
str obj1("Gautam");
cout<<"\n\n1st string:"<<obj1.p;
str obj2(" Naik");
cout<<"\n\n2nd string:"<<obj2.p;
str obj3;
obj3 = obj1+obj2;
cout<<"\n\nconcatenated string:"<<obj3.p;
getch();
return 0;
}

Output:
x: 10
y: 20
z: 30

After --:
x: 9
y: 19
z: 29

Before:
x: 1
y: 2
z: 3

After ++:
x: 2
y: 3
z: 4



For binary operator->

1st string:Gautam

2nd string: Naik

concatenated string:Gautam Naik

No comments:

Post a Comment