一、題目:
class String { public: String(const char *str = NULL); // 普通構造函數 String(const String &other); // 拷貝構造函數 ~String(void); // 析構函數 String & operator = (const String &other); // 賦值函數 private: char *m_data; // 用於保存字符串 };
各個解析:
1、構造函數
/*
1、構造函數在構造對象時使用;
2、傳入參數的判斷;
3、對象的初始化問題。
*/
String::String(const char *str) { if ( NULL == str) { m_data = new char[1] *m_data = '\0'; } else { int len = strlen(str); m_data = new char[len + 1]; strcpy(m_data,str); } }
2、拷貝構造函數
/*
1、拷貝構造函數必須在構造對象時使用,即定義對象時;
2、對象初始化問題。
*/
String::String(const String &other) { int len = strlen(other.m_data); m_data = new char[len+1]; strcpy(m_data,other.m_data); }
3、賦值函數
/*
1、賦值函數使用時,對象肯定已經建立;
2、賦值前,判斷是否是自我賦值;
3、賦值前,內存空間的准備:
由於賦值前,對象已占有一定大小內存,但是賦值對象所占內存大小與
對象已占的內存大小不一定一致;
先釋放對象已占的內存,然后分配心內存。
4、正常賦值
*/
String & String::operator = (const String &other) { if (&other == this) { return *this; } delete [] m_data; int len = strlen(other.m_data); m_data = new char[len+1]; strcpy(m_data,other.m_data); return *this; }
4、析構函數
/*
資源的釋放
*/
String::~String(void) { delete []m_data; }
5、拷貝構造函數與賦值函數相關知識
1、 拷貝構造函數與賦值函數的區別?
在看到“=”操作符為對象賦值的時候,
如果是在對象定義時(Test B = (Test)c),此時調用拷貝構造函數;
如果不是在對象定義賦值時(B = c),此時調用賦值函數。
注:構造函數、拷貝構造函數,帶有構造兩個字,顧名思義,就是在對象聲明或定義時才會使用。
2、拷貝構造函數與賦值函數定義的區別?
內存空間角度:
1)拷貝構造函數的使用,是在建立對象時;當時對象沒有占有內存,故不需要釋放內存,不重新建立內存空間。
2)賦值函數的使用,是在對象建立后;當時對象已經占有內存,故需要釋放先前內存,然后重新獲取內存空間。