I have a problem about char*, string add together such like this:
enter code here
s2 = s3 + "," + s1;
and I have three operator below
friend Mystring operator+( const Mystring &lhs, const Mystring &rhs); -- 1
friend Mystring operator+( const Mystring &mystr, const char *ch ); -- 2
friend Mystring operator+( const char *ch, const Mystring &mystr ); -- 3
but I use 1 and 3 it will crash, but I use 1 and 3 can do good.
My problem is the order isn't that s3 + "," first so use operator w first and the result use operator 3, but the fact isn't as my thought.
Can anyone explain why this happens?
Mystring operator+( const Mystring &mystr,const char *ch )
{
Mystring tmp;
tmp.str_ = new char[ strlen(mystr.str_)+2 ];
strcpy( tmp.str_, mystr.str_ );
strcat( tmp.str_, ch );
return tmp;
}
Mystring operator+( const char *ch, const Mystring &mystr )
{
Mystring tmp;
tmp.str_ = new char[ strlen(mystr.str_)+strlen(mystr.str_)+1 ];
strcpy( tmp.str_, mystr.str_ );
strcat( tmp.str_, mystr.str_ );
return tmp;
}
Mystring operator+( const Mystring &lhs, const Mystring &rhs )
{
Mystring tmp;
tmp.str_ = new char[ strlen(lhs.str_)+strlen(rhs.str_)+1 ];
strcpy( tmp.str_, lhs.str_ );
strcat( tmp.str_, rhs.str_ );
return tmp;
}