C-程序設(shè)計(jì)教學(xué)課件CHAPTER-5-CLASSES_第1頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-5-CLASSES_第2頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-5-CLASSES_第3頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-5-CLASSES_第4頁
C-程序設(shè)計(jì)教學(xué)課件CHAPTER-5-CLASSES_第5頁
已閱讀5頁,還剩70頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(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)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論