String类定义如下:
class String
{
public:
//普通构造函数
String(const char *str = nullptr);
//拷贝构造函数
String(const String& other);
//析构函数
~String();
//赋值运算符重载
String& operator= (const String& other);
private:
char * _data;
};
String普通构造函数实现
String::String(const char *str/* = nullptr*/)
{
if (str == nullptr)
{
_data = new char[1];
_data = '\0';
}
else
{
int len = strlen(str) + 1;
_data = new char[len];
memset(_data, 0, len);
strcpy(_data, str);
}
}
String拷贝构造函数实现
String::String(const String& other)
{
delete[]_data;
int len = strlen(other._data) + 1;
_data = new char[len];
memset(_data, 0, len);
strcpy(_data, other._data);
}
String析构函数实现
String::~String()
{
delete[]_data;
_data = nullptr;
}
String赋值运算符重载实现
String& String::operator=(const String& other)
{
if (this == &other)
{
return *this;
}
delete[]_data;
int len = strlen(other._data) + 1;
_data = new char(len);
memset(_data, 0, len);
strcpy(_data, other._data);
return *this;
}