




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
ObjectivesToabletodefineconstmemberfunctionsandconstobjectsTobeabletounderstandthethispointerToabletodefineandusestaticmembersTo
managedynamicmemorybyusingnewanddelete01ConstantMemberFunctionsandConstantObjects03StaticMembers02Thethispointers04FreeStore01ConstantMemberFunctionandConstantObjectsclass
Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;intgetMonth()const;~Date();private:intday,month,year;boolcheck();};ConstantMemberFunctionsConstantmemberfunctionsclass
Date{public:Date(int=2021,int=1,int=1);voidoutput();intgetDay();intgetMonth();~Date();private:intday,month,year;boolcheck();};int
Date::getMonth(){returnmonth;}int
Date::getDay(){returnday;}Definition:Usingkeywordconstdefinesconstantmemberfunctions.Theconstkeywordisplacedaftertheparameterlistinthe
functiondeclarationanddefinition.Thosefunctionsthatdonotmodifythedataofaclass,i.e.read-only,aredefinedasconstantmemberfunction.ConstantMemberFunctionsclass
Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;intgetMonth()const;~Date();private:intday,month,year;boolcheck();};int
Date::getMonth()const{returnmonth;}int
Date::getDay()const{returnday;}intmain(){Datetoday(2021,9,15);today.output();cout<<"Date:"<<today.getMonth()<<"-"<<today.getDay();return0;}int
Date::getMonth()const{
return++month;
}//errorConstantObjectsintmain(){Datetoday(2018,9,15);today.output();cout<<"Date:"<<today.getDay()<<endl;const
Dateday;//day.output();//errorcout<<"Date:"<<day.getDay()<<endl;return0;}constantobjectclass
Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;};Non-constantobjectAn
object
of
a
class
may
be
declaredtobeconst,justlikeanyotherC++variable.ConstantObjectsintmain(){Datetoday(2018,9,15);today.output();cout<<"Date:"<<today.getDay();const
Dateday;//day.output();//errorcout<<"Date:"<<day.getDay();return0;}Aconstmemberfunctioncanbeinvokedforbothconstantandnon-constantobjectsAnon-constmemberfunctioncanbeinvokedonlyfornon-constantobjectsTheconstpropertyofanobjectgoesintoeffectaftertheconstructorfinishesexecutingandendsbeforetheclass'sdestructorexecutes.Sotheconstructoranddestructorcanmodifythedatamembersoftheobject,butothermethods(i.e.functions)oftheclasscannot.02ThethisPointersThethisPointersThe
this
pointerisapointeraccessibleonlywithinthenon-staticmemberfunctionsofa
class.Thethispointerpointstotheobjectforwhichthefunctionwasinvoked.Butanobject’sthispointerisnotpartoftheobjectitself.thisisnotanordinaryvariablebecauseitisnon-modifiable-assignmentstothisarenotallowed.CaseStudy1:defineaDateclassThethisPointersvoid
Date::output(){cout<<
this->year<<
"-"
<<
this->month<<
"-"
<<
this->day<<endl;}class
Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;voidprintThis();private:intday,month,year;boolcheck();};void
Date::printThis(){cout<<
this
<<endl;}int
Date::getDay()const{return
this->day;}intmain(){Dateday1(2021,9,15);cout<<&day1<<endl;day1.printThis();cout<<
"Sizeoftheobject:"
<<
sizeof(day1)<<endl;Dateday2(2020,9,15);cout<<&day2<<endl;day2.printThis();cout<<
"Sizeoftheobject:"
<<
sizeof(day2)<<endl;return0;}001BFDC4001BFDC4Sizeoftheobject:12001BFDB0001BFDB0Sizeoftheobject:12ThethisPointersclass
Date{public:Date(int=2018,int=1,int=1);voidoutput();Date&reset(int,int,int);intgetDay()const;~Date();private:intday,month,year;boolcheck();};Date&Date::reset(int
y,int
m,int
d){this->year=y;this->month=m;this->day=d;return*this;}intmain(){Datetoday(2018,10,15);today.output();cout<<"Date:"<<(today.reset(2021,9,20)).getDay()<<endl;return0;}2018-10-15Date:20ObjectisdestroyedDate::~Date(){cout<<"Objectisdestroyed\n";}CaseStudy1-1:defineaDateclassRequirement:YouwillresetanewDatevaluebasedonthepreviousdefinitionofclassDateThethisPointerclass
Date{public:Date(int=2018,int=1,int=1);boolisEqual(Date&date);private:intday,month,year;boolcheck();};CaseStudy1-2:defineaDateclassRequirement:YoudeterminewhethertwoDateobjectsareequal.bool
Date::isEqual(Date&date){if(this->year==date.year&&this->month==date.month&&this->day==date.day)return
true;elsereturn
false;}intmain(){Dateday1(2021,9,15);Dateday2(2020,9,15);cout<<(day1.isEqual(day2)?"theyareequal":"theyareunequal")<<endl;return0;
}03StaticMembersStaticMembersDefineastudentclasswithastudentNodatamember.Youneedtodothefollowingtasks:OutputthedataofthestudentobjectsWorkoutthenumberofthestudentobjectsstudent-studentNo:int-count:int+student()+print():void+getCount():intCaseStudy2Dataabstraction:data:studentNo-intFunctionsPrint–voidprint()getCount-numberofstudentobjectsStaticMembersstudent::student()//constructor{count++;studentNo=count;}void
student::print(){cout<<
"studentNo:"
<<studentNo<<endl;}int
student::getCount(){
returncount;}intmain(){
studentst1;st1.print();cout<<st1.getCount()<<endl;
studentst2;st2.print();cout<<st2.getCount()<<endl;
studentst3;st3.print();cout<<st3.getCount()<<endl;
return0;}class
student{public:student();
voidprint();
intgetCount();private:
intcount=0;
intstudentNo=0;};Result:studentNo:11studentNo:11studentNo:11StaticMembersCountisnotdatamemberofthestudentclassintcount=0;class
student{public:student();
voidprint();
intgetCount();private:
intstudentNo=0;};student::student(){::count++;studentNo=::count;}void
student::print(){cout<<
"studentNo:"
<<studentNo<<endl;}int
student::getCount(){
return::count;}intmain(){
studentst1;st1.print();cout<<st1.getCount()<<endl;
studentst2;st2.print();cout<<st2.getCount()<<endl;
studentst3;st3.print();cout<<st3.getCount()<<endl;
return0;}studentNo:11studentNo:22studentNo:33StaticMembersclass
student{public:student();voidprint();private:intstudentNo=0;static
intcount;//thenumber};int
student::count=0;student::student(){count++;studentNo=count;}void
student::print(){cout<<"studentNo:"<<studentNo<<";count="<<count<<endl;}StaticdatamemberStaticdatamember’sinitialization:Mustbeplacedoutsidetheclass.intmain(){studentst1;st1.print();studentst2;st2.print();studentst3;st3.print();return0;}studentNo:1;count=1studentNo:2;count=2studentNo:3;count=3StaticMembersSt1StudentclassSt2St3countstudentNostudentNostudentNoStaticdatamember
isavariablethatispartofaclass,yetisnotpartofanobjectofthatclass.StaticMembersclass
student{public:student();//constructorvoidprint();private:intstudentNo=0;static
intcount;//thenumber};int
student::count=0;student::student()//constructor{count++;studentNo=count;cout<<
"count'saddress:"
<<&count<<endl;cout<<
"studentNo'saddress:"
<<&studentNo<<endl;}intmain(){
studentst1;cout<<
"st1'saddress:"
<<&st1
<<
"st1'ssize:"
<<
sizeof(st1)<<endl;studentst2;cout<<
"st2'saddress:"
<<&st2
<<
"st2'ssize:"
<<
sizeof(st2)<<endl;studentst3;cout<<
"st3'saddress:"
<<&st3
<<
"st3'ssize:"
<<
sizeof(st2)<<endl;return0;}count'saddress:0015D138studentNo'saddress:00EFFC90st1'saddress:00EFFC90st1'ssize:4count'saddress:0015D138studentNo'saddress:00EFFC84st2'saddress:00EFFC84st2'ssize:4count'saddress:0015D138studentNo'saddress:00EFFC78st3'saddress:00EFFC78st3'ssize:4StaticMemberFunctionsStaticmemberfunction
isafunctionthatneedsaccesstomembersofaclass,yetdoesnotneedtobeinvokedforaparticularobject.class
student{public:student();//constructorstatic
intgetCount();voidprint();private:intstudentNo;static
intcount;};Staticmemberfunctionint
student::count=0;student::student()//constructor{count++;studentNo=count;}void
student::print(){cout<<"studentNo:"<<studentNo<<endl;}int
student::getCount(){returncount;}StaticMember
Functionsclass
student{public:student();//constructorstatic
intgetCount();voidprint();private:intstudentNo;static
intcount;};Staticmemberfunctionint
student::count=0;student::student()//constructor{count++;studentNo=count;}void
student::print(){cout<<"studentNo:"<<studentNo<<endl;}int
student::getCount(){returncount;}intmain(){studentst1;st1.print();cout<<"studentnumberis"<<student::getCount()<<endl;studentst2;st2.print();cout<<"studentnumberis"<<student::getCount()<<endl;studentst3;st3.print();cout<<"studentnumberis"<<st3.getCount()<<endl;return0;}StaticMembersint
student::getCount(){studentNo++;//error:accesstonon-staticmember
returncount;//ok}Staticmemberfunctionsarenotattachedtoanyobject,thatis,theydonothavethispointer.Staticmemberfunctionscanonlyaccessstaticdatamembers.04FreeStoreFreeStoreLiteralconstdataStack(automaticstorage)Freestore(Heap)constantdataFunction’slocalvariables,arguments,returningdataandaddressPotentialavailablememoryGlobal(Staticdata)MemorylayoutGlobalandstaticvariablesintk1=1;intk2;static
intk3=2;static
intk4;intmain(){static
intm1=2,m2;inti=1;char*p;charstr[10]="hello";const
char*q="hello";p=(char*)malloc(100);free(p);return0;}FreeStore-dynamicmemoryAllmemoryneedsweredeterminedbeforeprogramexecutionbydefiningthevariableneeded.Buttheremaybecaseswherethememoryneedsofaprogramcanonlybedeterminedduringruntime.Whenthememoryneededdependonuserinput,
onthesecases,programsneedtodynamicallyallocateandfreememorybyusingnewanddeleteoperatorsinC++.FreeStore-dynamicmemory#include<typeinfo>intmain(){int*intp=new
int;*intp=20;int*intpt=new
int(8);cout<<typeid(intp).name()<<endl;cout<<typeid(intpt).name()<<endl;cout<<*intp<<""<<*intpt<<endl;deleteintp;deleteintpt;return0;}(malloc/freeinC)int*p=(int*)malloc(sizeof(p));AvoidmemoryleakResult:int*int*208QueriesinformationofatypeFreeStore-dynamicmemoryintmain(){intm;cout<<"Enteraninteger:";cin>>m;int*ptr=new
int[m];//dynamicone-dimensionalarrayif(ptr==NULL) cout<<"Error:memorycouldnotbeallocated";else{for(inti=0;i<m;i++)cin>>ptr[i];for(inti=0;i<m;i++)cout<<ptr[i]<<",";delete[]ptr;}int(*p)[4]=new
int[m][4];//dynamictwo-dimensionalarrayfor(inti=0;i<m;++i)for(intj=0;j<4;++j) p[i][j]=i*j;cout<<typeid(p).name()<<endl;delete[]p;return0;}FreeStoreObjectsAfreestoreobjectiscreatedusingthenewoperatoranddestroyedusingthedeleteoperator.
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 5 雷鋒叔叔你在哪里(教學(xué)設(shè)計(jì))-2023-2024學(xué)年統(tǒng)編版語(yǔ)文二年級(jí)下冊(cè)
- 9 古詩(shī)三首-雪梅教學(xué)設(shè)計(jì)2024-2025學(xué)年統(tǒng)編版語(yǔ)文四年級(jí)上冊(cè)
- 2024-2025學(xué)年高中化學(xué) 第4章 第2節(jié) 課時(shí)2 Cl2的實(shí)驗(yàn)室制法和Cl-的檢驗(yàn)教學(xué)實(shí)錄 新人教版必修1
- 2024-2025學(xué)年高中歷史 專(zhuān)題五 走向世界的資本主義市場(chǎng) 四 走向整體的世界(1)教學(xué)教學(xué)實(shí)錄 人民版必修2
- 1 吃水不忘挖井人(教學(xué)設(shè)計(jì))2024-2025學(xué)年統(tǒng)編版語(yǔ)文一年級(jí)下冊(cè)
- DB3709-T 005-2022 腦機(jī)接口康復(fù)訓(xùn)練系統(tǒng)臨床應(yīng)用規(guī)范
- 25《憶讀書(shū)》(教學(xué)設(shè)計(jì))-2024-2025學(xué)年統(tǒng)編版語(yǔ)文五年級(jí)上冊(cè)
- 2024年四年級(jí)英語(yǔ)上冊(cè) Unit 2 At Home Lesson 7 Homework教學(xué)實(shí)錄 冀教版(三起)
- 人工智能通識(shí)基礎(chǔ) 課件 第6章 人工智能課程實(shí)踐與設(shè)計(jì)
- 11葡萄溝教學(xué)設(shè)計(jì)-2024-2025學(xué)年統(tǒng)編版語(yǔ)文二年級(jí)上冊(cè)
- 2025-2031年中國(guó)法律培訓(xùn)行業(yè)市場(chǎng)深度分析及投資策略研究報(bào)告
- 危重患者營(yíng)養(yǎng)支持教學(xué)課件
- 《主題三 我的畢業(yè)季》說(shuō)課稿-2023-2024學(xué)年六年級(jí)下冊(cè)綜合實(shí)踐活動(dòng)遼師大版
- DeepSeek從入門(mén)到精通培訓(xùn)課件
- 北京市海淀區(qū)2024-2025學(xué)年八年級(jí)上學(xué)期期末考試數(shù)學(xué)試卷(含答案)
- 投行估值模型-洞察分析
- 《中國(guó)華北地區(qū)》課件
- 鐵死亡與腦缺血再灌注損傷
- 內(nèi)鏡粘膜下剝離術(shù)(ESD)
- 智能POS硬件設(shè)計(jì)
- 2024年四川護(hù)理職業(yè)學(xué)院高職單招職業(yè)技能測(cè)驗(yàn)歷年參考題庫(kù)(頻考版)含答案解析
評(píng)論
0/150
提交評(píng)論