stuck in operator overloading

#include<iostream>
#include<string.h>
using namespace std;
class string1
{
char *p;
int len;
public:
string1(){len=0;p=0;}
string1( char *s);
string1(const string1 & s);
~string1(){delete p;}
friend void operator=(const string1 & s1,const string1 & s2);
friend int operator==(const string1 & s1,const string1 & s2);
friend string1 operator+(const string1 & s1,const string1 & s2);
friend string1 operator>>(const string1 & s1);
friend int operator!(const string1 & s1);
friend int operator,(const string1 & s1,const string1 & s2);
friend void show (const string1 s);
};
string1 :: string1( char * s)
{
len=strlen(s);
p=new char [len+1];
strcpy(p,s);
}
string1 :: string1(const string1 & s)
{
len= s.len;
p=new char [len+1];
strcpy(p,s.p);
}
string1 operator+(const string1 &s1, const string1 &s2)
{
string1 temp;
temp.len=s1.len+s2.len ;
temp.p= new char(temp.len+1);
strcpy(temp.p,s1.p);
strcat(temp.p,s2.p);
return (temp);
}
int operator==(const string1 &s1, const string1 &s2)
{
int eql =0 ;
if(strcmp(s1.p,s2.p)==0)
{
eql=1;
}
return eql;
}
void operator=(const string1 &s1, const string1 &s2)
{
strcpy(s2.p,s1.p);

}

string1 operator>>(const string1 & s1)
{
strrev(s1.p);
}

string1 operator!(const string1 &s1, const string1 &s2)
{ strcpy(s2.p,s1.p);
strrev(s2.p);

if( strcmp(s1.p,s2.p) == 0 )
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");

}

void show (const string1 s)
{
cout<<s.p;
}
int main()
{ int op;
char a[20];
cout <<"\nenter 1st string";
cin.getline ( a, 20 );
cout <<"\n\n";
cout<< a;
string1 s1(&a[0]);
char b[20];
cout<<"\nenter 2st string(for no data give -1)\n";
cin.getline ( b, 20 );
string1 s2(&b[0]);
do{

cout<<"\nMENU\n"
<<"1.Check equality in length\n"
<<"2.Copy string\n"
<<"3.Concate string\n"
<<"4.To reverse a string\n"
<<"5.Check for palindrome\n"
<<"6.Quit\n";
cin>>op;
switch(op)
{
case 1:
if(s1==s2)
{
cout<<"Both are equal";
}
else {cout<<"Both are not equal";}
break;
case 2: s2=s1 ;
show (s2);
break;
case 3: string1 t=s1+s2;
show (t);
break;
case 4:
cout<<"\n";
>>s1;
break;
case 5: !s1;
break;
}
}
while(op!=6);

return 0;
}
Last edited on
Can you please edit your post and use the code formatting tag to format your code.

Also, can you please describe what the problem is.

Thanks.
The copy assignment operator shall be a member of the class. So instead of

friend void operator=(const string1 & s1,const string1 & s2);

You should declare

string1 & operator =( const string1 &s );
Last edited on
Topic archived. No new replies allowed.