轉載自:https://blog.csdn.net/tianzez/article/details/79636250
class String {
public:
String(const char *str = ""); // 默認構造函數
String(const String& copy); // 拷貝構造函數
~String(); // 析構函數
String& operator = (const String& assign); // 賦值函數
private:
size_t m_size; // 當前當前長度
char *m_data; // 指向字符串的指針
};
// 構造函數
String::String(const char *str = NULL)
{
if (NULL == str) {
m_data = new char[1];
*m_data = '\0';
m_size = 0;
}else {
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
m_size = length;
}
}
// 構造拷貝函數
String::String(const String& other){
size_t len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
m_size = len;
}
// 析構函數
String::~String()
{
delete[]m_data;
}
// 賦值函數
String& String::operator=(const String& other)
{
if (this != &other) { //(1)檢查自賦值
char* temp = new char[strlen(other.m_data) + 1]; //(2)分配新的內存資源,並複製內容
strcpy(temp, other.m_data);
delete[]m_data; //(3)釋放原本的內存資源
m_data = temp;
m_size = strlen(other.m_data);
}
return *this; //(4)返回本對象的引用
}