C++ operator overloading problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • abnair
    New Member
    • May 2014
    • 1

    #1

    C++ operator overloading problem

    I am trying out operator overloading. I have following code:

    Code:
    class Mystring{
       public:
          Mystring(char* ch)
          {
             data = new char[strlen(ch)*4];
             strcpy(data,ch);
          }
          friend Mystring operator+(Mystring& s1, Mystring& s2);
          friend ostream& operator<<(ostream& out, Mystring& s1);
       char *data;
    };
    Mystring operator+( Mystring& s1, Mystring& s2)
    {
       Mystring temp(s1.data);
       strcat(temp.data,s2.data);
       return temp;
    }
    ostream& operator<<(ostream& out, Mystring& s1)
    {
       out<<s1.data;
       return out;
    }
    In main I have defined two Mystring object.
    Code:
    Mystring s1("Abhilash");
    Mystring s2("Nair");
    Following two statements work fine.
    Code:
    Mystring s3=s1+s2;
    cout<<s3<<endl;
    But when I do
    Code:
    cout<<s1+s2<<endl;
    I get compiler error. I am using cygwin compiler.

    Below is the error I get. Why do you think it is happening?
    Last edited by Banfa; May 15 '14, 10:38 AM.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Actually giving the error you got would make this easier to diagnose however you could try

    cout<<(s1+s2)<< endl;

    Comment

    Working...