編寫類String的建構函式、拷貝建構函式、解構函式和賦值函式
阿新 • • 發佈:2019-01-02
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)賦值函式的使用,是在物件建立後;當時物件已經佔有記憶體,故需要釋放先前記憶體,然後重新獲取記憶體空間。