注意运算符的重载即可:
class My_String
{
private:
char* str;
public:
My_String()
{
str = nullptr;
}
My_String(const char* src)
{
if(src!=nullptr)
{
int len = strlen(src) + 1;
str = new char[len];
memmove(str, src, sizeof(char) * len);
}
}
My_String(const My_String& src)
{
int len = strlen(src.str) + 1;
str = new char[len];
memmove(str, src.str, sizeof(char) * len);
}
~My_String()
{
delete[]str;
str = nullptr;
}
void print()const
{
cout << str << endl;
}
My_String& operator=(const My_String& cp)
{
if (this != &cp)
{
delete[]this->str;
int len = strlen(cp.str) + 1;
str = new char[len];
memmove(str, cp.str, sizeof(char) * len);
}
return*this;
}
My_String operator+(const My_String& cp)const
{
My_String tmp;
int len = strlen(this->str) + strlen(cp.str) + 1;
tmp.str = new char[len];
strcpy_s(tmp.str, len, this->str);
strcat_s(tmp.str, len, cp.str);
return tmp;
}
My_String& operator+=(const My_String& cp)
{
My_String tmp;
int len = strlen(this->str) + strlen(cp.str) + 1;
tmp.str = new char[len];
strcpy_s(tmp.str, len, this->str);
strcat_s(tmp.str, len, cp.str);
delete[]this->str;
this->str = tmp.str;
tmp.str = nullptr;
return*this;
}
My_String operator+(const char* cp)const
{
My_String tmp;
int len = strlen(this->str) + strlen(cp) + 1;
tmp.str = new char[len];
strcpy_s(tmp.str, len, this->str);
strcat_s(tmp.str, len, cp);
return tmp;
}
char& operator[](const int n)
{
assert(this!=nullptr&&n >= 0&&n <= (strlen(this->str)));
return this->str[n];
}
int Sz()const
{
return strlen(this->str);
}
char*& Get()
{
return this->str;
}
friend My_String operator+(const char* cpy, My_String& cp);
};
My_String operator+(const char * cpy,My_String& cp)
{
My_String tmp;
int len = strlen(cpy) + strlen(cp.str )+ 1;
tmp.str = new char[len];
strcpy_s(tmp.str, len, cpy);
strcat_s(tmp.str, len, cp.str);
return tmp;
}
int main()
{
My_String s1{ "guorui" };
My_String s2{ "xiaomao" };
My_String s3;
s3 = s1;
s3.print();
s3 = s1 + s2;
s3.print();
s3 = s1 += s2;
s3.print();
s3 = s1 + "and";
s3.print();
s3 = "xy" + s2;
s3.print();
char ch = s2[2];
cout << ch <<endl;
return 0;
}
需要注意的只有,字符串+对象 这个+的重载与对象+对象与对象+字符串都互不相同,字符串+对象需要用到友元函数。(不然就十分麻烦)
可以看到,我只进行了+,=以及[]的重载。还有许多C++中string类提供的方法与运算符重载我并没有实现,只是实现了几个比较关键的。