Tuesday, 9 June 2015

Program to illustrate operator overloading for strings



Code for Program to illustrate operator overloading for strings in C++ Programming



 



 
#include<iostream.h>
 #include<string.h>
 #include<conio.h>

 /*************************************************************************///------------------------------  string  -------------------------------///*************************************************************************/classstring
    {
       private:
        char str[80];

       public:
        string()  { strcpy(str,"ttt"); }
        string(char s[])  { strcpy(str,s); }
        void display()  { cout<<str<<endl; }
        stringoperator+(string );
    };


 /*************************************************************************///--------------------------  operator+(string)  ------------------------///*************************************************************************/stringstring::operator+(string ss)
    {
       string temp;

       if(strlen(str)+strlen(ss.str)<80)
      {
         strcpy(temp.str,str);
         strcat(temp.str,ss.str);
      }

       else
      {
         cout<<"string overflow"<<endl;
         temp=0;
      }
       return temp;
    }


 main()
    {
       clrscr();

       string s1(" Best Wishes");
       string s2(" Happy New Year");
       string s3;

       s1.display();
       s2.display();

       s3=s1+s2;

       s3.display();

       getch();
       return 0;
    }

No comments:

Post a Comment