模拟实现
class string
{
public:
//字符串构造
string(const char *str = "")
{
if (nullptr == str)//若传入空指针报错
{
assert(false);
return;
}
_size = strlen(str) + 1;
_capacity = _size;
_str = new char[_capacity + 1];
strcpy(_str, str);
}
//拷贝构造
string(const string& str)
:_str(new char[str._capacity+1])
,_size(str._size)
, _capacity(str._capacity)
{
strcpy(_str, str._str);
}
//运算符重载
string& operator=(const string& str)
{
if (this != &str)//检查是否自拷贝
{
char* ptr = new char[str._capacity+ 1];//运算符重载需要新开辟一块内存,交换拷贝,因为_str已经开辟过了,只用重新指向就好了
strcpy(ptr,str._str);
delete[] _str;//释放原指向空间
_str = ptr;
_size = str._size;
_capacity = str._capacity;
}
return *this;
}
//析构
~string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
int _size;
int _capacity;
char* _str;
};