首页 > 代码库 > string类的构造和析构
string类的构造和析构
class String
{
public:
String(const char * str);
String(const String & other);
~String();
String& operator=(const String & other);
private:
char * m_data;
}
String::~String()
{
delete [] m_data;
}
String::String(const char * str)
{
if(str == NULL)
{
m_data = http://www.mamicode.com/new char[1];
m_data[0] = ‘\0‘;
}
else
{
int length = strlen(str);
m_data = http://www.mamicode.com/new char[length + 1];
strcpy(m_data, str);
}
}
String::String(const String & other)
{
int length = strlen(other.m_data);
m_data = http://www.mamicode.com/new char[length + 1];
strcpy(m_data, other.m_data);
}
String & String::operator=(const String & other)
{
if(this == &other)
return *this; //如果地址相同时,直接返回
delete [] m_data; //释放原来的内存
int length = strlen(other.m_data);
m_data = http://www.mamicode.com/new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
string类的构造和析构