Operator overloading is a very useful chapter in C++. Here is a C++ program demonstrating the technique of overloading binary operator. Hope this will be helpful to students.
#include< iostream.h >
#include< conio.h >
#include< string.h >
class Count
{
private:
char str1 [10], str2 [10];
public:
void get ()
{
cout<< "Enter the 1st string: -";
cin>>str1;
cout<< "Enter the 2nd string: -";
cin>>str2;
}
char *operator + ()
{
strcat (str1, str2);
return str1;
}
};
void main ()
{
clrscr ();
Count c1;
char str3 [20];
c1.get ();
strcpy (str3, +c1);
cout<< "\nAfter Concatenate ="<< str3;
getch ();
}
We have used different string manipulating functions in C++ programs. Suppose we wand to append one string at the end of other string, we normally invoke library function strcat(). The same operation can done using the + operator through operator overloading in C++ programs. Similar related operations can also be done.
#include< iostream.h >
#include< conio.h >
#include< string.h >
class String
{
private:
char str [100];
public:
String ()
{
strcpy (str," ");
}
String (char ch [])
{
strcpy (str, ch);
}
void display ()
{
cout<< endl<< str;
}
String operator + (String s)
{
String t;
strcpy (t.str, str);
strcat (t.str, s.str);
return t;
}
};
void main ()
{
clrscr ();
String s1, s2,s3;
s1="Satavisha ";
s2="Suddhashil";
s1.display ();
s2.display ();
s3=s1+s2;
s3.display ();
getch ();
}
Any doubt or question can be asked through comments.
No comments:
Post a Comment