




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
C++ProgrammingCHAPTER5CLASSES1
5.1Introduction
5.2ClassesandObjects
5.3ConstructorsandtheDestructor
5.4Composition
5.5Friends25.1IntroductionStructuredProgrammingvs.Object-OrientedProgrammingStructural(Procedural)Object-OrientedPROGRAMPROGRAMFUNCTIONOBJECTOperationsFUNCTIONDataOBJECTFUNCTIONOBJECTOperationsOperationsDataData35.1IntroductionObject-OrientedProgrammingLanguageFeatures1.DataabstractionTgrammermustestablishtheassociationbetweenthemachinemodelandthemodeloftheproblemthatisactuallybeingsolved.45.1IntroductionExample:Dataabstraction-ClockclassClock{public://CodeabstractionvoidSetTime(intNewH,intNewM,intNewS);voidShowTime();private://DataabstractionintHour,Minute,Second;5};5.1Introduction2.InformationhidingInanobject-orientedlanguage,aclassisarmationhiding.InaC++class,wecanusekeywordssuchaspublicandprivatetocontrolaccesstotheclass’spropertiesandoperations.Wecanusethekeywordpublictoexposetheclass’erfaceandthekeywordprivatetohideitsimplementation.65.1IntroductionExample:Informationhiding-ClockclassClock{public:voidSetTime(intNewH,intNewM,intNewS);voidShowTime();private:intHour,Minute,Second;};75.1Introduction3.IpertiesClassescanbestand-aloneortheycanoccurininheritancehierarchies,whichconsistofparent/childrelationshipsamongclasses.85.1Introduction4.PolymorphismThetermpolymorphismmeanshavingmanyforms.Polymorphismallowsimprovedcodeorganizationandreadabilityaswellasthegramsthatcanbe“grown”notonlyduringtheoriginalcreationject,butalsowhennewfeaturesaredesired.95.1IntroductionOOPTermsC++EquivalentsObjectClassobjectorclassinstanceInstancevariablePrivatedatamemberMethodPublicmemberfunctionMessagepassingFunctioncall(toapublicmemberfunction)105.2ClassesandObjectsClassesClassesInC++,aclassisadatatype.Inobject-orienteddesign,aclassisacollectionofobjects.Operties,features,orattributes.115.2ClassesandObjectsClassessyntax:classclassname{public:publicmembers(interface)private:privatemembersprotected:protectedmembers12};5.2ClassesandObjectsClassesInC++,themembervariablesorfieldsarecalleddatamembers.Thefunctionsthatbelongtoaclassarecalledfunctionmembers.Inobject-orientedlanguagesgenerally,suchfunctionsarecalledmethods.135.2ClassesandObjectsClassesExample:classHuman{private:char*Name;//datamemberschar*Id;public:voidSetName(char*cpName);//methodsvoidGetName(char*cpName);voidSetId(char*cpId);voidGetId(char*cpId);14};5.2ClassesandObjectsClassesExample:classClock{public:voidSetTime(intNewH,intNewM,intNewS);voidShowTime();private:intHour,Minute,Second;};155.2ClassesandObjectsClassesvoidClock::SetTime(intNewH,intNewM,intNewS){Hour=NewH;Minute=NewM;Second=NewS;}voidClock::ShowTime(){cout<<Hour<<":"<<Minute<<":"<<Second;16}5.2ClassesandObjectsClassesRemarks:A)Methodscanbeimplementedeitherinsideoroutsidethedeclarationoftheclass.Ifthemethodsareimplementedoutsidetheclass,andscoperesolutionshouldbeused.175.2ClassesandObjectsClassesB)Ifthemethodsareimplementedinsidetheclass,thentheyturntobetheinlinefunctions.Oryoucanusethekeywordinlinetodeclareaninlinefunction.185.2ClassesandObjectsClassesExample:classPoint{public:voidInit(intinitX,intinitY){X=initX;Y=initY;}intGetX(){returnX;}intGetY(){returnY;}private:intX,Y;19};Example:classPoint{inlinevoidPoint::Init(intinitX,intinitY){public:X=initX;Y=initY;voidInit(intinitX,intinitY);intGetX();intGetY();}private:inlineintPoint::GetX(){intX,Y;};returnX;}inlineintPoint::GetY(){returnY;}205.2ClassesandObjectsClassesC)Methodscanbedeclaredtobeoverloadingordefaultarguments.215.2ClassesandObjectsObjectsObjectsIfHumanisauser-defineddatatypeinC++,wecandefinedavariablesuchasmaryLeakeytorepresenttheobjectwhobelongstotheclassofhumanbeings.Example:HumanmaryLeakey;//createanobject225.2ClassesandObjectsObjectsRemark:Aebeforethedefinitionofanyobjects.235.2ClassesandObjectsMemberAccessMemberAccessInsidetheclass,membersareaccesseddirectlybynames.Outsidetheclass,publicmembersareaccessedbytheway“object.member”.245.2ClassesandObjectsMemberAccessExample:#include<iostream>spacestd;classClock{voidmain(void){ClockmyClock;......//myClock.SetTime(8,30,30);myClock.ShowTime();};}255.2ClassesandObjectsThisThisObjectsofoneclasshavethereowndatamembersandsharethesamecopyofmethods.265.2ClassesandObjectsThisobject1object2object3data1data2data1data2data1data2method1method2275.2ClassesandObjectsThisEverymethodhaveanthispointer.Thethispointertellspilerwhichobjectaccessthemethod.Example:voidClock::SetTime(intNewH,intNewM,intNewS){this->Hour=NewH;this->Minute=NewM;this->Second=NewS;28}5.3ConstructorsandtheDestructorsConstructorsConstructorsAconstructoristhe.Asuitableconstructorisinvokedautomaticallywheneveraninstanceoftheclassiscreated.29Example:classPerson{public:Person();Person(conststring&n);Person(constchar*n);voidsetName(conststring&n);voidsetName(constchar*n);conststring&getName()const;private:;};30Person::Person(conststring&n){name=n;}Person::Person(constchar*n){name=n;}intmain(){Personanonymous;Personjc(“J.Coltrane”);return0;}315.3ConstructorsandtheDestructorsConstructorsRemarks:A)Ifaconstructorisnotdefined,adefaultconstructorwillbeinvokedautomaticallyforeachobject.B)Aconstructorcanbeinlinefunction,overloadingfunctionanddefaultargumentsfunction.32Example1:#include<iostream>spacestd;classClock{public:Clock(intNewH,intNewM,intNewS);//ConstructorvoidSetTime(intNewH,intNewM,intNewS);voidShowTime();private:intHour,Minute,Second;};33Clock::Clock(intNewH,intNewM,intNewS){Hour=NewH;Minute=NewM;Second=NewS;}voidmain(){Clockc(0,0,0);//Constructorisinvokedc.ShowTime();}34Example2:classClock{public:Clock(intNewH);Clock(intNewH,intNewM);Clock(intNewH,intNewM,intNewS);//Constructorprivate:intHour,Minute,Second;};35Clock::Clock(intNewH,intNewM,intNewS){Clock::Clock(intNewH){Hour=NewH;Minute=0;Second=0;Hour=NewH;Minute=NewM;Second=NewS;}Clock::Clock(intNewH,intNewM)}{voidmain()Hour=NewH;Minute=NewM;Second=0;{Clocka(1);Clockb(1,2);Clockc(1,2,3);}36}5.3ConstructorsandtheDestructorsConstructorsQuestion:Hgramusingdefaultargumentsfunction?375.3ConstructorsandtheDestructorsTheCopyConstructor
CopyconstructorcreatesanewobjectasacopyofanotherTheCopyConstructorobject.Syntax:classClassName{public:ClassName(arguments);//constructorClassName(ClassName&object);//copyconstructor...38};5.3ConstructorsandtheDestructorsTheCopyConstructorClassName::ClassName(ClassName&object)//copyconstructor{//……}395.3ConstructorsandtheDestructorsTheCopyConstructorExample:classPoint{public:Point(intxx=0,intyy=0){X=xx;Y=yy;}Point(Point&p);intGetX(){returnX;}intGetY(){returnY;}private:intX,Y;40};5.3ConstructorsandtheDestructorsTheCopyConstructorPoint::Point(Point&p){X=p.X;Y=p.Y;cout<<"copyconstructorisinvoked."<<endl;}415.3ConstructorsandtheDestructorsTheCopyConstructorRules:A)Ifanobjectisinitializedbyanotherobjectofthesameclass,thecopyconstructorisinvokedautomatically.425.3ConstructorsandtheDestructorsTheCopyConstructorExample:voidmain(void){PointA(1,2);PointB(A);//copyconstructorisinvokedcout<<B.GetX()<<endl;}435.3ConstructorsandtheDestructorsTheCopyConstructorB)Iftheargumentsofthefunctionisanobjectofaclass,thecopyconstructorisinvokedwhenthefunctionisinvoked.445.3ConstructorsandtheDestructorsTheCopyConstructorExample:voidfun1(Pointp){cout<<p.GetX()<<endl;}voidmain(){PointA(1,2);fun1(A);//copyconstructorisinvoked45}5.3ConstructorsandtheDestructorsTheCopyConstructorC)Ifthefunctionreturnsanobjectofaclass,thecopyconstructorisinvoked.465.3ConstructorsandtheDestructorsTheCopyConstructorExample:Pointfun2(){PointA(1,2);returnA;//copyconstructorisinvoked}voidmain(){PointB;B=fun2();47}5.3ConstructorsandtheDestructorsTheCopyConstructorRemarks:TheC++compilerwillstillautomaticallycreateacopyconstructor,defaultprimitivebehavior:abitcopy,ifyoudon’tmakeone.485.3ConstructorsandtheDestructorsTheCopyConstructorExample:Defaultcopyconstructorcanonlycopythemembersoftheobjectbybitcopy.Object1ResourceObject2User-definedcopyconstructorcancopytheresource,too.Object1ResourceObject2Resource495.3ConstructorsandtheDestructorsDestructorsDestructorsThedestructorisautomaticallyinvokedwheneveranobjectbelongingtoaclassisdestroyed.505.3ConstructorsandtheDestructorsDestructorsSyntax:classClassName{public:ClassName(arguments);ClassName(ClassName&object);~ClassName();//destructor};ClassName::~ClassName()//destructor{//……51}5.3ConstructorsandtheDestructorsDestructorsRemarks:A)Thedestructortakesnoargumentsandcannotbeoverloaded.B)Thedestructorhasnoreturntype.C)TheC++compilerwillautomaticallycreateadestructorifwedon’tmakeit.52Example:#include<iostream>spacestd;classPoint{public:Point::Point(intxx,intyy){Point(intxx,intyy);~Point();//...X=xx;Y=yy;}Point::~Point(){}private:intX,intY;};535.3ConstructorsandtheDestructorsDestructorsCode545.4CompositionYousimplycreateobjectsofyourexistingclassinsidethenewclass.Thisiscalledcompositionbecausethenewclassiscomposedofobjectsofexistingclasses.555.4CompositionExample:classPoint{private:floatx,y;public:Point(floath,floatv);floatGetX(void);loatGetY(void);voidDraw(void);56};5.4CompositionclassLine{private:Pointp1,p2;public:Line(Pointa,Pointb);VoidDraw(void);};575.4CompositionTheConstructorInitializerListWhenanobjectiscreated,pilerguaranteesthatconstructorsforallofitssubobjectsarecalled.Thenewclassconstructordoesn’thavepermissiontoaccesstheprivatedataelementsofthesubobject,soitcan’tinitializethemdirectly.585.4CompositionTheConstructorInitializerListThesolutionissimple:Calltheconstructorforthesubobject.C++providesaspecialsyntaxforthis,theconstructorinitializerlist.595.4CompositionTheConstructorInitializerListSyntax:ClassName::ClassName(argument1,argument2,……):subobject1(argument1),subobject2(argument2),......{//……}605.4CompositionOrderofConstructor&DestructorcallsConstructor:1)memberobjectconstructors2)constructoroftheclassDestructor:destructorarecalledinexactlythereverseorderoftheconstructors615.4CompositionOrderofConstructor&DestructorcallsIfthedefaultconstructorisinvoked,thedefaultmemberobjectconstructorsareinvoked,too.625.4CompositionOrderofConstructor&DestructorcallsExample:classPart{public:Part();Part(inti){val=i;}~Part();voidPrint();private:intval;};635.4CompositionOrderofConstructor&DestructorcallsclassWhole{public:Whole();Whole(inti,intj,intk);~Whole();voidPrint();private:Partone;Parttwo;intdata;64};5.4CompositionOrderofConstructor&DestructorcallsWhole::Whole(){data=0;}Whole::Whole(inti,intj,intk):two(i),one(j),data(k){}//...655.5FriendsTheC++languageusesprivateandprotectedtohidetheimplementationoftheclass.Whatifyouwanttoexplicitlygrantaccesstoafunctionthatisn’tamemberofthecurrentclass?665.5FriendsItisaccomplishedbydeclaringthatfunctionafriendinsidethestructuredeclaration.It’simportantthatthefrienddeclarationoccursinsidethestructuredeclarationbec
溫馨提示
- 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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 衡陽師范學(xué)院《馬克思主義哲學(xué)(下)》2023-2024學(xué)年第二學(xué)期期末試卷
- 電子科技大學(xué)中山學(xué)院《車輛建模與仿真》2023-2024學(xué)年第二學(xué)期期末試卷
- 甘肅省蘭州市第六十三中學(xué)2025屆高三3月期初測試化學(xué)試題含解析
- 武漢科技大學(xué)《數(shù)字化教學(xué)資源設(shè)計(jì)與開發(fā)(C)》2023-2024學(xué)年第二學(xué)期期末試卷
- 許昌職業(yè)技術(shù)學(xué)院《植物保健與和諧植?!?023-2024學(xué)年第二學(xué)期期末試卷
- 湖南吉利汽車職業(yè)技術(shù)學(xué)院《日本文學(xué)》2023-2024學(xué)年第二學(xué)期期末試卷
- 工程造價(jià)領(lǐng)域發(fā)展趨勢
- 工程教育基礎(chǔ)
- 廠房強(qiáng)化護(hù)欄施工方案
- 屋面設(shè)備基礎(chǔ)施工方案
- 第二單元 煥發(fā)青春活力 大單元教學(xué)設(shè)計(jì)-2024-2025學(xué)年統(tǒng)編版道德與法治七年級下冊
- 2025年陜西延長石油集團(tuán)有限責(zé)任公司招聘筆試參考題庫含答案解析
- 河南退役軍人專升本計(jì)算機(jī)真題答案
- 2024年湖南省中考英語試題卷(含答案)
- 小學(xué)語文新課標(biāo)學(xué)習(xí)任務(wù)群的基本理解和操作要領(lǐng)
- 催化材料智慧樹知到答案章節(jié)測試2023年南開大學(xué)
- 績效評價(jià)師考試-隨機(jī)題庫
- 專利申請文件 審查意見的答復(fù)
- 美的集團(tuán)優(yōu)秀員工評選管理辦法
- 區(qū)塊鏈項(xiàng)目資金申請報(bào)告范文
- 進(jìn)貨檢驗(yàn)指引及流程到貨物料包裝、數(shù)量、質(zhì)量檢查辦法
評論
0/150
提交評論