版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 增强护理新技术与新进展
- 香皂项目可行性研究报告
- 2026年家庭急救心肺复苏海姆立克常识操作规范试题
- 2026年中小企业合规建设指引知识竞赛
- 2026年医疗行业专业知识多选题库
- 2026年预防未成年人犯罪法及不良行为干预严重不良行为矫治测试
- 2026年医保药品目录更新与考核内容
- 年产500万尾海水鱼苗工厂化培育量产可行性研究报告
- 2026年空军征兵职业能力测试题库及答案
- 2026年国际关系理论与实践国际移民治理与政策协调考试题目
- 2025年自贡市中考物理试题卷(含答案解析)
- 产品返修件管理制度
- 篮球裁判员手册(2人执裁与3人执裁2018年版)
- 共享单车投放合作协议书
- 烧烤营地合作协议书
- 黑龙江省园林绿化工程消耗量定额2024版
- 人工智能助力智慧护理的发展
- 公路工程标准施工招标文件第八章-工程量清单计量规则(2018年版)
- 危险化学品安全有关法律法规解读
- 2025年初中语文名著阅读《林海雪原》知识点总结及练习
- 公共数据授权运营的垄断隐忧与对策
评论
0/150
提交评论