Example:22
Declare a class named “string” with attribute as str. Take input for two objects calculate and print their sum (concatenate) using overloaded binary operator “+”.
//Add (Concatenate) two string1
//using overloaded operator "+"
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class string1
{
char str[20];
public:
void read();
void show();
string1 operator+(string1 s);
};
void string1::read()
{
cout<<"Enter any string1 ";
cin>>str;
}
void string1::show()
{
cout<<"string1 is "<<str<<endl;
}
string1 string1::operator+(string1 s1)
{
string1 t;
strcpy(t.str,str);
//strcat(t.str," ");
strcat(t.str,s1.str);
return(t);
}
int main()
{
string1 e1,e2,e3;
e1.read();e2.read();
e1.show();e2.show();
e3=e1+e2; //e3=e1.operator+(e2);
e3.show();
getch();
return(0);
}
Output:
Enter any string1 Hello
Enter any string1 Computer
string1 is Hello
string1 is Computer
string1 is HelloComputer
Example:23
Declare a class named “string” with attributes as str. Take input for two objects calculate and print their sum (concatenate) using overloaded binary operator “+” with friend function.
//Add (Concatenate) two string1
//using overloaded operator "+"
//Using friend function
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class string1
{
char str[20];
public:
void read();
void show();
friend string1 operator+(string1 s1,string1 s2);
};
void string1::read()
{
cout<<"Enter any string1 ";
cin>>str;
}
void string1::show()
{
cout<<"string1 is "<<str<<endl;
}
string1 operator+(string1 s1,string1 s2)
{
string1 t;
strcpy(t.str,s1.str);
//strcat(t.str," ");
strcat(t.str,s2.str);
return(t);
}
int main()
{
string1 e1,e2,e3;
e1.read();e2.read();
e1.show();e2.show();
e3=e1+e2; //e3=operator+(e1,e2);
e3.show();
getch();
return(0);
}
Output:
Enter any string1 Hello
Enter any string1 World
string1 is Hello
string1 is World
string1 is HelloWorld




