Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

/*Write a program that substitutes an overloaded += operator

for the overloaded + operator in the STRPLUS program in this chapter. This
operator should allow statements like
s1 += s2;
where s2 is added (concatenated) to s1 and the result is left in s1. The operator
should also permit the results of the operation to be used in other calculations,
as in
s3 = s1 += s2;
*/
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;

class String
{
private:
static const int SIZE=80;
char str[SIZE];
public:
String(){strcpy(str,"");}
String(char s[]){strcpy(str,s);}
void display()const{cout<<str;}
String operator +(String ss)const;
String operator +=(String ss);
};

int main()
{
String s1="Merry Christmas!";
String s2="Happy new year!";
String s3;

cout<<"s1= ";s1.display();
cout<<"\ns2= ";s2.display();
cout<<"\ns3= ";s3.display();

s3=s1+s2;
cout<<"\ns3(=s1+s2)= ";s3.display();cout<<endl;

s1="Hello";
s2="World";

cout<<"s1= ";s1.display();
cout<<"\ns2= ";s2.display();
cout<<"\ns3= ";s3.display();
s3=s1+s2;
cout<<"\ns3(=s1+s2)= ";s3.display();
s1+=s2;
cout<<"\ns1(after s1+=s2)= ";s1.display();
cout<<"\ns2(after s1+=s2)= ";s2.display();
s3=s1+=s2;
cout<<"\ns3(after s3=s1+=s2)= ";s3.display();
cout<<endl;

return 0;
}
String String::operator + (String ss)const
{
String temp;
if(strlen(str)+strlen(ss.str)<SIZE)
{
strcpy(temp.str,str);
strcat(temp.str, ss.str);
}
else
{
cout<<"\nString overflow.\n";
exit(1);
}

return temp;
}

String String::operator+=(String ss)


{
if(strlen(str)+strlen(ss.str)<SIZE)
{
strcat(str, ss.str);
}
else
{
cout<<"\nString overflow.\n";
exit(1);
}

return String(str);
}

You might also like