私有变量只有一个指针
char * p;
字符串构造函数
MyString(const char * s=NULL) {
if (s) {
p = new char[strlen(s) + 1];
strcpy(p, s);
}
else {
p = new char[1];
p[0] = '\0';
}
}
析构函数
~MyString() { if (p) delete[] p; }
拷贝构造函数
MyString(const MyString &s) {
if (s.p) {
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
else {
p = new char[1];
p[0] = '\0';
}
}
输出重载函数
friend ostream & operator<< (ostream & os, MyString &s) {
os << s.p;
return os;
}
赋值运算符重载右边为MyString对象
MyString& operator = (const MyString &s) {
if (p == s.p)
return *this;
if (p != NULL)
delete p;
if (s.p) {
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
else {
p = new char[1];
p[0] = '\0';
}
return *this;
}
赋值运算符重载,右边为字符串
MyString & operator=(const MyString & s){
if (p == s.p)
return *this;
if(p!=NULL)
delete[] p;
if (s.p){
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
else{
p = new char[1];
p[0] = '\0';
}
return *this;
}
三个字符串比较重载函数
bool operator <(MyString &s2) {
return strcmp(p, s2.p) == -1;
}
bool operator >(MyString &s2) {
return strcmp(p, s2.p) == 1;
}
bool operator ==(MyString &s2) {
return strcmp(p, s2.p) == 0;
}
加法重载
MyString operator+(MyString &s2) {
char* p_ = new char[strlen(p) + strlen(s2.p) + 1];
strcpy(p_, p);
strcat(p_,s2.p);
return MyString(p_);
}
+=重载
MyString & operator+=(const char *s)
{
char* temp = new char[strlen(p)+1];
strcpy(temp, p);
delete[] p;
p = new char[strlen(temp) + strlen(s)+1];
strcpy(p, temp);
strcat(p, s);
return *this;
}
friend MyString operator+(const char * str, MyString s )
{
char *temp = new char[strlen(str) + strlen(s.p)+1];
strcpy(temp,str);
strcat(temp, s.p);
return MyString(temp);
}
friend MyString operator+(MyString s, const char *str)
{
char *temp = new char[strlen(s.p) + strlen(str) + 1];
strcpy(temp, s.p);
strcat(temp, str);
return MyString(temp);
}