class myString
{
public:
myString& operator=(char* s);
myString& operator=(const myString& s);
char& operator[](int i);//重载[],实现数组运算
const char& operator[](int i)const;
myString& operator+=(const myString& s);
myString& operator+=(const char* s);
friend ostream& operator<<(ostream& out,myString& s);
friend istream& operator>>(istream& in,myString& s);
friend bool operator<(const myString& left,const myString& right);
friend bool operator>(const myString& left,const myString& right);
friend bool operator==(const myString& left,const myString& right);
friend bool operator!=(const myString& left,const myString& right);
char* getData();//获取data指针
int length();
private:
int size;
char *data;
};
myString& myString::operator=(char* s)
{
if (data!=NULL)
{
delete []data;
}
size = strlen(s);
data = new char[size+1];
strcpy(data,s);//复制目标字符串
return *this;
}
myString& myString::operator =(const myString& s)
{
if (this==&s)
{
return *this;
}
if (data != NULL)
{
delete []data;
}
size = strlen(s.data);
data = new char[size+1];
strcpy(data,s.data);
return *this;
}
char& myString::operator[](int i)
{
return data[i];
}
const char& myString::operator [](int i)const
{
return data[i];
}
myString& myString::operator+=(const myString& s)//
{
int len = size + s.size + 1;
char *temp = data;
data = new char[len];
size = len - 1;
strcpy(data,temp);
strcat(data,s.data);
delete []temp;
return *this;
}
myString& myString::operator+=(const char* s)
{
if (s==NULL)
{
return *this;
}
int len = size + strlen(s) + 1;
char *temp = data;
data = new char[len];
size = len - 1;
strcpy(data,temp);
strcat(data,s);
delete []temp;
return *this;
}
int myString::length()
{
return size;
}
ostream& operator<<(ostream &out,myString &s)
{
for (int i = 0;i<s.length();i++)
{
out << s[i] << " ";
}
return out;
}
istream& operator>>(istream& in,myString& s)
{
char p[50];
in.getline(p,50);
s = p;
return in;
}
bool operator<(const myString& left,const myString& right)
{
int i = 0;
while (left[i]==right[i]&&left[i]!=0&&right[i]!=0)
{
i++;
}
return left[i]-right[i] < 0?true:false;
}