class String
{
public:
String(const char * str = NULL); //普通构造函数
String(const String &other); //复制构造函数
String & operator= (const String &other); //赋值操作符
~String(); //析构函数
private:
char *m_data;
};
String::String(const char *str)
{
if (str == NULL)
{
m_data = new char[1];
m_data[1] = '\0';
}
else
{
int lenght = strlen(str);
m_data = new char[lenght + 1];
strcpy(m_data, str);
}
}
String::String(const String &other)
{
int lenght = strlen(other.m_data);
m_data = new char[lenght + 1];
strcpy(m_data, other.m_data);
}
String & String::operator= (const String &other)
{
if(&other == this) //证同测试
return *this;
delete [] m_data;
int lenght = strlen(other.m_data);
m_data = new char[lenght + 1];
strcpy(m_data, other.m_data);
return *this; //第一次写的时候忘记返回*this
}
String & String::operator= (const String &other)
{
String temp(other);
// delete [] m_data;
swap(m_data, other.m_data);
return *this; //又忘记返回*this
}
String::~String()
{
delete [] m_data;
}
编写类String的构造/析构函数,赋值操作符
最新推荐文章于 2020-08-15 23:15:09 发布