




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第五章類:初始化和清除面向?qū)ο蟪绦蛟O(shè)計(jì)(C++)5.3初始化和清除構(gòu)造函數(shù)析構(gòu)函數(shù)何時(shí)被調(diào)用默認(rèn)構(gòu)造函數(shù)與重載構(gòu)造函數(shù)5.3.1安全性要求正確地初始化和清除對象是保證程序安全性的關(guān)鍵問題!intmain(){StashintStash;
intStash.initialize(sizeof(int));//初始化
for(inti=0;i<100;i++){
intStash.add(&i);}……;
intStash.cleanup();//清除}5.3.2構(gòu)造函數(shù)5.3.2.1
構(gòu)造函數(shù):確保初始化類的特殊成員函數(shù),編譯器在創(chuàng)建對象時(shí)自動(dòng)調(diào)用該函數(shù)。通常做一些初始化動(dòng)作。以保證同一個(gè)類的對象具有一致性。構(gòu)造函數(shù)跟類同名,可以帶參數(shù),沒有返回值。跟別的成員函數(shù)沒有名字沖突;編譯器總能知道調(diào)用哪一個(gè)函數(shù);例:帶構(gòu)造函數(shù)的StashclassStash{
intsize;//Sizeofeachspace…;public:
Stash(intsize);//構(gòu)造函數(shù),跟類同名,無返回值
int
add(void*element);…;voidcleanup();};Stash::Stash(int
sz){size=sz;quantity=0;storage=0;next=0;}自動(dòng)初始化Stash對象intmain(){//創(chuàng)建對象時(shí)自動(dòng)調(diào)用構(gòu)造函數(shù)StashintStash1(2),intStash2(2);
for(inti=0;i<100;i++){intStash1.add(&i);}……;intStash1.cleanup();//清除}說明構(gòu)造函數(shù)的名字必須與類的名字相同;構(gòu)造函數(shù)不允許指明返回類型,也不允許返回一個(gè)值;構(gòu)造函數(shù)應(yīng)聲明為public(但不是必須),否則無法創(chuàng)建對象。classStash{
private:
Stash(int
sz){…};
…};voidmain(){
Stashs(10);//Error!can‘taccessprivatemember}說明(續(xù))可以重載構(gòu)造函數(shù);classStash{public:Stash(){size=1;…;}
Stash(int
sz){…}…};voidmain(){StashcharStash;StashintStash(2);StashintStash(10,2);//error,參數(shù)不匹配!}5.3.3析構(gòu)函數(shù)5.3.3.1析構(gòu)函數(shù):確保清除析構(gòu)函數(shù):類的特殊成員函數(shù),在撤銷對象時(shí)自動(dòng)調(diào)用該函數(shù)。通常做一些撤銷對象前的回收工作。析構(gòu)函數(shù)不帶參數(shù),沒有返回值;不能夠重載。析構(gòu)函數(shù)必須是public函數(shù)。例:String類ClassString{private:char*str;public:
String(char*s);//構(gòu)造函數(shù),跟類同名
String(unsigned
int
sz);//重載構(gòu)造函數(shù)
…;
~String();//析構(gòu)函數(shù),類名前面加上一個(gè)~};
String::~String(){deletestr;}String::String(unsigned
int
sz){//不能有返回值;if(sz>0)str=newchar[sz];elsestr=newchar[100];}String::String(char*s){//不能有返回值;
int
len;
len=strlen(s);if(len<100)len=100;
str=newchar[len];
strcpy(str,s);}voidmain(){StringPaper_Tiger(“U.S.A.”);}//退出主程序前撤銷對象,調(diào)用析構(gòu)函數(shù)5.3.4何時(shí)被執(zhí)行?5.3.4.1
何時(shí)被執(zhí)行?構(gòu)造函數(shù):當(dāng)對象被創(chuàng)建時(shí),調(diào)用構(gòu)造函數(shù);析構(gòu)函數(shù):當(dāng)對象被撤銷時(shí),調(diào)用析構(gòu)函數(shù)。//此例說明何時(shí)調(diào)用構(gòu)造函數(shù)和析構(gòu)函數(shù)//類的定義classTree{
intheight;public:
Tree(int
initialHeight);//構(gòu)造函數(shù)
~Tree();//析構(gòu)函數(shù)
voidgrow(intyears);voidprintsize();};//類的實(shí)現(xiàn)Tree::Tree(int
initialHeight){height=initialHeight;printsize();}Tree::~Tree(){
cout<<"insideTreedestructor";
}voidTree::grow(intyears){height+=years;}voidTree::printsize(){
cout<<"Treeheightis"<<height<<endl;}intmain(){
cout<<"beforeopeningbrace"<<endl;{ Treet(12);//生成t
cout<<"afterTreecreation"<<endl; t.grow(4);
cout<<"beforeclosingbrace"<<endl;}//此時(shí)撤銷t;
cout<<"afterclosingbrace"<<endl;}///:~beforeopeningbraceafterTreeCreationbeforeclosingbraceinsideTreedestructor//執(zhí)行析構(gòu)函數(shù)Treeheightis16afterclosingbrace5.3.5完整的類5.3.5.1
完整的類
完整的類通常具有的特征:數(shù)據(jù)抽象:數(shù)據(jù)成員&成員函數(shù)實(shí)現(xiàn)隱藏;(訪問控制)自動(dòng)初始化和清除;(構(gòu)造函數(shù)和析構(gòu)函數(shù))例:類Stash//Withconstructors&destructors#ifndefSTASH2_H#defineSTASH2_HclassStash{
intsize;//Sizeofeachspace
intquantity;//Numberofstoragespaces
intnext;//Nextemptyspace
//Dynamicallyallocatedarrayofbytes:unsignedchar*storage;voidinflate(intincrease);public://:C06:Stash2.h
Stash(intsize); ~Stash();
int
add(void*element); void*fetch(intindex);
intcount();};#endif//STASH2_H///:~//Constructors&destructors#include"Stash2.h"#include"../require.h"#include<iostream>#include<cassert>usingnamespacestd;constintincrement=100;//:C06:Stash2.cppStash::Stash(int
sz){//構(gòu)造函數(shù)
size=sz;quantity=0;storage=0;next=0;}int
Stash::add(void*element){
if(next>=quantity)inflate(increment);//Copyelementintostorage,//startingatnextemptyspace:
int
startBytes=next*size; unsignedchar*e=(unsignedchar*)element;
for(inti=0;i<size;i++)
storage[startBytes+i]=e[i]; next++;
return(next-1);//Indexnumber}void*Stash::fetch(intindex){ require(0<=index,"Stash::fetch(-)index");
if(index>=next)return0;//Toindicatetheend//Producepointertodesiredelement:return&(storage[index*size]);}int
Stash::count(){returnnext;//NumberofelementsinCStash}voidStash::inflate(intincrease){
require(increase>0,"Stash::inflatezeroornegativeincrease");
int
newQuantity=quantity+increase;
int
newBytes=newQuantity*size;
int
oldBytes=quantity*size;unsignedchar*b=newunsignedchar[newBytes];
for(inti=0;i<oldBytes;i++)
b[i]=storage[i];//Copyoldtonewdelete[](storage);//Oldstoragestorage=b;//Pointtonewmemoryquantity=newQuantity;}Stash::~Stash(){
if(storage!=0){
cout<<"freeingstorage"<<endl;
delete[]storage;}}///:~//:C06:Stash2Test.cpp#include"Stash2.h"#include"../require.h"#include<fstream>#include<iostream>#include<string>usingnamespacestd;intmain(){StashintStash(sizeof(int));
for(inti=0;i<100;i++)
intStash.add(&i);
for(intj=0;j<intStash.count();j++)
cout<<"intStash.fetch("<<j<<")="<<*(int*)
intStash.fetch(j)<<endl;constint
bufsize=80;StashstringStash(sizeof(char)*bufsize);
ifstreamin("Stash2Test.cpp");
assure(in,"Stash2Test.cpp");stringline;
while(getline(in,line))
stringStash.add((char*)line.c_str());
intk=0;char*cp;
while((cp=(char*)stringStash.fetch(k++
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024~2025學(xué)年廣東廣州八年級下冊4月期中數(shù)學(xué)試題【帶答案】
- 導(dǎo)尿袋清潔標(biāo)準(zhǔn)考核試卷
- 供應(yīng)鏈質(zhì)量管理與紡織品市場考核試卷
- 生物分子網(wǎng)絡(luò)分析工具考核試卷
- 糖業(yè)環(huán)保技術(shù)集成與創(chuàng)新合作考核試卷
- 操作專題規(guī)程資料
- 控制系統(tǒng)與儀器設(shè)備匹配性分析考核試卷
- 2025年中國PE螺紋管數(shù)據(jù)監(jiān)測研究報(bào)告
- 2025年中國POF膜收縮機(jī)數(shù)據(jù)監(jiān)測研究報(bào)告
- 2025年中國LED隧道燈數(shù)據(jù)監(jiān)測報(bào)告
- ××中學(xué)實(shí)驗(yàn)室?;饭芾砑?xì)則
- 家政服務(wù)培訓(xùn) 課件
- 2025年婚姻家庭咨詢師職業(yè)資格考試試題及答案
- 2025年人教版小學(xué)五年級下冊數(shù)學(xué)期末重難點(diǎn)測評試題(含答案和解析)
- 2024年天津市應(yīng)急管理局招聘行政執(zhí)法專職技術(shù)檢查員筆試真題
- GB/T 13173-2021表面活性劑洗滌劑試驗(yàn)方法
- 小學(xué)45年級必背古詩課件
- QC基礎(chǔ)知識(shí)培訓(xùn)材料課件
- 從知溝到數(shù)字鴻溝課件
- 《企業(yè)員工培訓(xùn)國內(nèi)外文獻(xiàn)綜述》4800字
- 客戶確認(rèn)單(標(biāo)準(zhǔn)模版)
評論
0/150
提交評論