seo優(yōu)化操作淘寶怎么優(yōu)化關(guān)鍵詞步驟
析構(gòu)函數(shù)
析構(gòu)函數(shù)于構(gòu)造函數(shù)相對應(yīng),構(gòu)造函數(shù)是對象創(chuàng)建的時候自動調(diào)用的,而析構(gòu)函數(shù)就是對象在銷毀的時候自動調(diào)用的
特點:
1)構(gòu)造函數(shù)可以有多個來構(gòu)成重載,但析構(gòu)函數(shù)只能有一個,不能構(gòu)成重載
2)構(gòu)造函數(shù)可以有參數(shù),但析構(gòu)函數(shù)不能有參數(shù)
3)與構(gòu)造函數(shù)相同的是,如果我們沒有顯式的寫出析構(gòu)函數(shù),那么編譯器也會自動的給我們加上一個析構(gòu)函數(shù),什么都不做;如果我們顯式的寫了析構(gòu)函數(shù),那么將會覆蓋默認的析構(gòu)函數(shù)
4)在主函數(shù)中,析構(gòu)函數(shù)的執(zhí)行在return
語句之前,這也說明主函數(shù)結(jié)束的標志是return
,return
執(zhí)行完后主函數(shù)也就執(zhí)行完了,就算return
后面還有其他的語句,也不會執(zhí)行的
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson op1;system("pause");return 0;
}
運行結(jié)果
Beginning
從這里也可以發(fā)現(xiàn),此時析構(gòu)函數(shù)并沒有被執(zhí)行,它在system
之后,return
之前執(zhí)行
指針對象執(zhí)行析構(gòu)函數(shù)
與棧區(qū)普通對象不同,堆區(qū)指針對象并不會自己主動執(zhí)行析構(gòu)函數(shù),就算運行到主函數(shù)結(jié)束,指針對象的析構(gòu)函數(shù)也不會被執(zhí)行,只有使用delete
才會觸發(fā)析構(gòu)函數(shù)
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson *op2 = new Cperson;delete(op2);system("pause");return 0;
}
運行結(jié)果
Beginning
End
在這里可以發(fā)現(xiàn),已經(jīng)出現(xiàn)了End
,說明析構(gòu)函數(shù)已經(jīng)被執(zhí)行,也就說明了delete
觸發(fā)了析構(gòu)函數(shù)
臨時對象
格式:類名();
作用域只有這一條語句,相當于只執(zhí)行了一個構(gòu)造函數(shù)和一個析構(gòu)函數(shù)
除了臨時對象,也有臨時變量,例如語句int(12);
就是一個臨時變量,當這句語句執(zhí)行完了,變量也就釋放了,對外部沒有任何影響,我們可以通過一個變量來接受這一個臨時的變量,例如:int a=int(12);
這與int a=12;
不同,后者是直接將一個整型數(shù)值賦給變量a
,而前者是先創(chuàng)建一個臨時的變量,然后再將這個變量賦給變量a
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson();system("pause");return 0;
}
運行結(jié)果
Beginning
End
析構(gòu)函數(shù)的作用
當我們在類中聲明了一些指針變量時,我們一般就在析構(gòu)函數(shù)中進行釋放空間,因為系統(tǒng)并不會釋放指針變量指向的空間,我們需要自己來delete
,而一般這個delete
就放在析構(gòu)函數(shù)里面
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){pp = new int;cout << "Beginning" << endl;}~Cperson(){delete pp;cout << "End" << endl;}private:int *pp;
};int main()
{Cperson();system("pause");return 0;
}
malloc、free和new、delete的區(qū)別
malloc
不會觸發(fā)構(gòu)造函數(shù),但new
可以
free
不會觸發(fā)析構(gòu)函數(shù),但delete
可以
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){pp = new int;cout << "Beginning" << endl;}~Cperson(){delete pp;cout << "End" << endl;}private:int *pp;
};int main()
{Cperson *op1 = (Cperson *)malloc(sizeof(Cperson));free(op1);Cperson *op2 = new Cperson;delete op2;system("pause");return 0;
}
運行結(jié)果
Beginning
End
從結(jié)果上來看,只得到了一組Beginning、End
說明只有一組觸發(fā)了構(gòu)造函數(shù)和析構(gòu)函數(shù),這一組就是new和delete