#include <iostream>
#include<cstring>
using namespace std;
class mystring
{
public:
mystring();
mystring(const char *s);
mystring(mystring &obj);
~mystring();
mystring operator+(const mystring &obj);
mystring operator+(const char *s);
mystring& operator=(const mystring &obj);
mystring& operator=(const char *s);
mystring& operator+=(const mystring &obj);
mystring& operator+=(const char *s);
bool operator==(const mystring &obj);
bool operator==(const char *s);
char operator[](int index);
int size();
friend ostream& operator<<(ostream &ot,mystring &s);
friend istream& operator>>(istream &it,mystring &s);
private:
char *str;
};
mystring::mystring()
{
str=new char [1];
*str='\0';
}
mystring::mystring(const char *s)
{
str=new char [strlen(s)+1];
strcpy(str,s);
}
mystring::mystring(mystring &obj)
{
if(this==&obj)
return ;
delete []str;
str=new char [strlen(obj.str)+1];
strcpy(str,obj.str);
}
mystring::~mystring()
{
delete []str;
}
mystring mystring::operator+(const mystring &obj)
{
mystring temp;
temp.str=new char [strlen(this->str)+strlen(obj.str)+1];
strcpy(temp.str,this->str);
strcat(temp.str,obj.str);
return temp;
}
mystring mystring::operator+(const char *s)
{
mystring temp;
temp.str=new char [strlen(this->str)+strlen(s)+1];
strcpy(temp.str,this->str);
strcat(temp.str,s);
return temp;
}
mystring& mystring::operator=(const mystring &obj)
{
if(this==&obj)
{
return *this;
}
delete [] str;
this->str=new char [strlen(obj.str)+1];
strcpy(this->str,obj.str);
return (*this);
}
mystring& mystring::operator=(const char *s)
{
if(strcmp(str,s)==0)
return *this;
delete []str;
this->str=new char [strlen(s)+1];
strcpy(str,s);
return *this;
}
mystring& mystring::operator+=(const mystring &obj)
{
char buf[100]={0};
strcpy(buf,this->str);
delete this->str;
str=new char [strlen(this->str)+strlen(obj.str)+1];
strcpy(str,buf);
strcat(str,obj.str);
return *this;
}
mystring& mystring::operator+=(const char *s)
{
char buf[100]={0};
strcpy(buf,this->str);
delete this->str;
str=new char [strlen(this->str)+strlen(s)+1];
strcpy(str,buf);
strcat(str,s);
return *this;
}
bool mystring::operator==(const mystring &obj)
{
if(strlen(str)!=strlen(obj.str))
return false;
for(int i=0;i<strlen(str);i++)
{
if(str[i]!=obj.str[i])
return false;
}
return true;
}
bool mystring::operator==(const char *s)
{
if(strlen(str)!=strlen(s))
return false;
for(int i=0;i<strlen(str);i++)
{
if(str[i]!=s[i])
return false;
}
return true;
}
char mystring::operator[](int index)
{
return str[index];
}
int mystring::size()
{
return strlen(str);
}
//测试
int main()
{
mystring s1("hello "),s2("world"),s3,s4;
#if 0
//cin ,cout
cout<<"iput s4"<<endl;
cin>>s4;
cout<<"s4:"<<s4<<endl;
//+ ,=
s3=(s1+s2);
cout<<"s1+s2="<<s3<<endl;
//cout<<s1+s2<<endl;
//==
mystring s5("asdfg"),s6("hello");
if(s5==s6)
cout<<"s5=s6"<<endl;
else
cout<<"s5!=s6"<<endl;
//+=
s1+=s2;
cout<<"s1+=s2"<<s1<<endl;
#endif
mystring a1,a2("wlecom to");
a1="hello world";
a1=a2+" good "+a1;
cout<<a1<<endl;
}