【GeekBand】C++筆記(2)

一、析構(gòu)函數(shù)的主要作用就是:釋放資源,避免內(nèi)存泄漏。


? ? ? ?如果類里面只用到的基本類型,如int char double等,系統(tǒng)的默認(rèn)析構(gòu)函數(shù)其實什么都沒有做

但如果你使用了其他的類如vector,string等,系統(tǒng)的默認(rèn)析構(gòu)函數(shù)就會調(diào)用這些類對象的析構(gòu)函數(shù)。

? ? ? ?平時使用中也一定要注意:

? ? ? ? ? ? ? ? ?對于指針型成員變量(動態(tài)分配內(nèi)存的)要先釋放內(nèi)存。

二、關(guān)于String類的例子:


class String

{

public:

? ? ~ String(void); // 析構(gòu)函數(shù)

? ? String(const char* str = NULL);//普通構(gòu)造函數(shù)

? ? String(const String &other);//拷貝構(gòu)造函數(shù)

? ? String &operate = (const String &other);//賦值操作

private:

? ? char * m_data;

}


// String 的析構(gòu)函數(shù)

String::~String(void)

{

? ? delete [] m_data;

}


// String 的普通構(gòu)造函數(shù)

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);

? ? }

}


// 拷貝構(gòu)造函數(shù)

String::String(const String &other)

{

? ? int length = strlen(other.m_data);

? ? m_data = new char[length+1];

? ? strcpy(m_data, other.m_data);

}


// 賦值函數(shù)

String & String::operate =(const String &other)

{

? ? // (1) 檢查自賦值

? ? if(this == &other)

? ? return *this;

? ? // (2) 釋放原有的內(nèi)存資源

? ? delete [] m_data;

? ? // (3)分配新的內(nèi)存資源,并復(fù)制內(nèi)容

? ? int length = strlen(other.m_data);

? ? m_data = new char[length+1];

? ? ?strcpy(m_data, other.m_data);

? ? ?// (4)返回本對象的引用

? ? ?return *this;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容