函數原型
class String
{
public:
String(const char* str = "");
~String();
String(const String& other);
String&::operator=(const String& other);
};
String的普通構造函數
String::String(const char* str)
{
if (str == NULL)
{
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::~String()
{
delete []m_data;
}
String的拷貝構造函數
String::String(const String& other)
{
int length = strlen(other.m_data);
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
String&::operator=(const String& other)
{
if (this != other)
{
char* temp = new char[strlen(other.m_data) + 1];
strcpy(temp,other.m_data);
delete []m_data;
m_data = temp;
}
return *this;
}