String的构造函数、析构函数和赋值数

时间:2022-12-17 19:27:35

 

 /*
编写类String的构造函数、析构函数和赋值函数,已知类String的原理为:
class String
{
public:
String(const char *str=NULL);
String(const String &other);
~String(void);
String& operator=(const String &other);
private:
char *m_data;
};
String::String(const char *str=NULL)
{
if(NULL==str)
{
m_data=new char[1];
*m_data='\0';
}
else
{
int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data,str);
}
}
String::String(const String &other)
{
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
}
String::~String(void)
{
delete m_data;
}
String& String::operator=(const String &other);
{
if(this==&other)
{
return *this;
}
delete m_data;
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
return *this;
}
*/