版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C++ProgrammingChapter3ClassesandObjectsIndex1Ogramming2ClassesandObjects2.1Classes2.2Objects2.3this3ConstructorsandDestructors3.1Constructors3.2TheCopyConstructor3.3Destructors4CompositionIndex5Static5.1StaticDataMembers5.2StaticMemberFunctions6Constant6.1ConstantObjects6.2ConstantMemberFunctionsChap.3ClassesandObjects1Ogramming1OgrammingTherealworldProgramminglanguageThingsAbstractObjectsinstanceattributesbehaviorsAbstractInstantiateClassesAnewtypedatamethods1Ogramming
StructuredProgrammingvs.Object-OrientedProgrammingStructural(Procedural)Object-OrientedProgramProgramFUNCTIONCLASSOperationsFUNCTIONDataCLASSCLASSOperationsFUNCTIONOperationsDataData1OgrammingTheBlueprintofthecarclassobjects....IndependentofothersChap.3ClassesandObjects2ClassesandObjects2.1Classes
InC++,aclassisadatatype,Inobject-orienteddesign,aclassisacollectionofobjects.
Syntax:classclass_name{public:publicmembers(interface)private:privatemembersprotected:protectedmembers};2.1Classes
Accesscontrolmodifier:controlaccesstoclasses’member
Public:canbeaccessedanywhere
Protected:canbeaccessedbyselfclass,subclassandfriendfunction
private:
canbeaccessedbyselfclassandfriendfunction
Defaultaccesscontrolmodifierformember2.1Classes
InC++,themembervariablesorfieldsarecalleddatamembers.
Thefunctionsthatbelongtoaclassarecalledfunctionmembers.
Inobject-orientedlanguagesgenerally,suchfunctionsarecalledmethods.2.1ClassesExample:classClock{public:voidSetTime(intNewH,intNewM,intNewS);voidShowTime()//Functionmembers{//Definedinsidetheclasscout<<Hour<<":"<<Minute<<":"<<Second;}private:intHour,Minute,Second;//Datamembers};2.1ClassesvoidClock::SetTime(intNewH,intNewM,intNewS){//DefinedoutsidetheclassHour=NewH;Minute=NewM;Second=NewS;}
Remarks:
Methodscanbeimplementedeitherinsideoroutsidethedeclarationoftheclass.Ifthemethodsareimplementedinsidetheclass,thentheyturntobetheinlinefunctions.Ifthemethodsareimplementedoutsidetheclass,theandscoperesolutionshouldbeused.
2.2Objects
Objects
Theinstanceofclasses
Avariableoftheuser-defineddatatypes
wecandefined:
Object:ClockmyClock;
Objectpointer:Clock*myClock;
Objectreference:Clock&myClock;2.2Objects
Insidetheclass,wecanaccessanytypeofmembers,andmembersareaccesseddirectlybynames.
Outsidetheclass
Privatememberscannotbeaccessed
ToObjectandobjectreference,membersareaccessedby“.”myClock.showTime();
ToObjectpointer,membersareaccessedby“->”pClock->showTime();2.2ObjectsExample:intmain(){Clocks1,s2,*ps;s1.setTime(18,34,56);s2.setTime(9,0,0);ps=&s2;s1.showTime();ps->showTime();return0;Output:18:34:569:0:0}2.3this
Objectsofoneclasshavetheirowndatamembersandsharethesamecopyofmethods.object1object2object3data1data2data1data2data1data2method1method22.3this
thispointer
Everyobjecthasathispointer
Thispointerpointstotheobjectitself
Callinganon-staticmemberfunctionofanobject
Thethispilerwhichobjectaccessthefunction.
thispointer,asanimplicitparameter,ispassedtoeveryfunction2.3thisExample:voidClock::SetTime(intNewH,intNewM,intNewS,/*Clock*this*/){this->Hour=NewH;this->Minute=NewM;this->Second=NewS;}2.3this
Globalvariablesandfunctions:inoneclass,howtoaccesstheglobalvariablesandfunctions.Example:intn=0;classCTest{//globalvariableintn;intdemo(){cout<<::n<<‘\n’;//usetheglobalvariablencout<<n<<‘\n’;}}Chap.3ClassesandObjects3ConstructorsandDestructors3.1Constructors
Howtoinitializedatamember?
Inthedefinitionofclass?Example:private:inta=100;//Wecannotknowwhichobjectthedatabelongto!
Assignvaluetodatamemberofobject?Example:clockc={8,30,10};//Datamemberisprivate!
Defineainitializingfunctionmember?Example:voidinitiate{hour=8;minute=30;second=20}//Itistootired!
Constructors:Initializethedatamemberofanobjectwhentheobjectiscreated3.1Constructors
Aconstructorisamethod
Wis.
Automaticallycalledwhenanobjectiscreated
Withoutreturntype
Canbeoverloaded:Asuitableconstructorisinvokedautomaticallywheneveraninstanceoftheclassiscreated.
Canbedefaultargumentsfunction3.1ConstructorsExample:classclock{private:inthour,minute,second;public:clock(){hour=8;minute=0;second=0;cout<<"theclockis"<<hour<<":"<<minute<<":"<<second<<endl;}clock(intpHour,intpMinute,intpSecond){hour=pHour;minute=pMinute;second=pSecond;cout<<"theclockis"<<hour<<":"<<minute<<":"<<second<<endl;}};3.1Constructorsintmain(){clockc1;clockc2(12,30,50);return0;}Output:Theclockis8:0:0Theclockis12:30:503.1Constructors
Defaultconstructors
Ifaclasshasnoconstructor,adefaultconstructorwillbeinvoked.
Thedefaultconstructorjustcreatesobjectwithoutanyinitialization.
Ifaclasshasaconstructor,C++videdefaultconstructor.3.2Destructors
Thedestructorisautomaticallyinvokedwheneveranobjectbelongingtoaclassisdestroyed.classClassName{public:ClassName(arguments);ClassName(ClassName&object);~ClassName();//destructor};ClassName::~ClassName()//destructor{//……}3.2Destructors
Remarks:
Thedestructortakesnoargumentsandcannotbeoverloaded.
Thedestructorhasnoreturntype.
TheC++compilerwillautomaticallycreateadestructorifwedon’tmakeit.3.3TheCopyConstructor
Copyconstructorcreatesanewobjectasacopyofanotherobject.
Syntax:classClassName{public:ClassName(arguments);//constructorClassName(ClassName&object);//copyconstructor...};3.3TheCopyConstructorExample:classPoint{public:Point(intxx=0,intyy=0){X=xx;Y=yy;}Point(Point&p){X=p.X;Y=p.Y;cout<<"copyconstructorisinvoked."<<endl;}intGetX(){returnX;}intGetY(){returnY;}private:intX,Y;};3.3TheCopyConstructor
A)IfanobjectisinitializedbyanotherobjectoftheRules:sameclass,thecopyconstructorisinvokedautomatically.Example:voidmain(void)Output:copyconstructorisinvokedcopyconstructorisinvoked11{PointA(1,2);PointB(A);//copyconstructorisinvokedPointC=A;//copyconstructorisinvokedcout<<B.GetX()<<“”<<C.GetX()<<endl;}3.3TheCopyConstructor
B)IftheargumentsofthefunctionisanobjectofaRules:class,thecopyconstructorisinvokedwhenthefunctionisinvoked.voidfun1(Pointp){cout<<p.GetX()<<endl;}Output:voidmain(){copyconstructorisinvokedPointA(1,2);fun1(A);//copyconstructorisinvoked1}3.3TheCopyConstructor
C)Ifthefunctionreturnsanobjectofaclass,theRules:copyconstructorisinvoked.Pointfun2(){PointA(1,2);returnA;//copyconstructorisinvoked}voidmain(){PointB;B=fun2();Output:}copyconstructorisinvoked3.3TheCopyConstructor
Ifaclasshasresource,copymaybe:
Shallowcopy
Defaultcopyconstructor
OnlycopytheaddressoftheresourceObject1ResourceObject2
Deepcopy
User-definedcopyconstructor
CancopytheresourceObject1ResourceObject2ResourceExample1Example2Chap.3ClassesandObjects4Composition4Composition
Composition
Createobjectsofyourexistingclassinsidethenewclass.
Tposedofobjectsofexistingclasses(calledsubobject).
Enhancethereusabilityofsoftware4CompositionExample:classPoint{private:classLine{private:floatx,y;public:Pointp1,p2;Point(floath,floatv);floatGetX(void);floatGetY(void);voidDraw(void);public:Line(Pointa,Pointb);VoidDraw(void);};};4Composition
Theinitializationofsubobject
Whenanobjectiscreated,itssubobjectsshouldbeinitialized
Thenewclassconstructordoesn’thavepermissiontoaccesstheprivatedataelementsofthesubobject,soitcan’tinitializethemdirectly
Simplesolution:calltheconstructorforthesubobject4Composition
OrderofConstructor&Destructorcalls
Constructor:
1)memberobjectconstructors
2)constructoroftheclass
Destructor:
destructorarecalledinexactlythereverseorderoftheconstructors
Ifthedefaultconstructorisinvoked,thedefaultmemberobjectconstructorsareinvoked,too.
Question:canweconstructthesubobjectinthebodyofclassconstructor?4Composition
MemberinitializerlistSyntax:ClassName::ClassName(argument1,argument2,……):subobject1(argument1),subobject2(argument2),......{//……}
Example:WholeandPart4Composition
Question:canweinitiatetheconstmemberorreferencememberinthebodyofclassconstructor?
Memberinitializerlistmondatamembers,referencedatamembersandconstmembers.classSillyClass{public:SillyClass(int&i):ten(10),refI(i){}protected:ten;int&refI;};Chap.3ClassesandObjects5Static5.1StaticDataMembers
Staticdatamember
Thereisasinglepieceofstorageforastaticdatamember,regardlessofhowmanyobjectsofthatclassyoucreate.
Itisawayforthemto“communicate”witheachother.
Thestaticdatabelongstotheclass;isscopedinsidetheclassanditcanbepublic,private,orprotected.
Remarks:
Alltheobjectsownonecopyofthestaticdatamembersinaclass.
Staticdatamembersmustbeinitializedoutsidetheclass.5.1StaticDataMembersExample:#include<iostream>spacestd;classPoint{public:Point(intxx=0,intyy=0){X=xx;Y=yy;countP++;}Point(Point&p);intGetX(){returnX;}intGetY(){returnY;}voidGetC(){cout<<"Objectnum="<<countP<<endl;}private:intX,Y;countP;};5.1StaticDataMembersPoint::Point(Point&p){X=p.X;Y=p.Y;countP++;}intPoint::countP=0;//initializedoutsidetheclassPointvoidmain(){PointA(4,5),B;A.GetC();PointC(A);C.GetC();Output:Objectnum=1Objectnum=3}5.2StaticMemberFunctions
Staticmemberfunctions
Likestaticdatamembers,staticmemberfunctionsworkfortheclassratherthanforaparticularobjectofaclass.
Staticmemberfunctionscanonlyaccessthestaticdatamemberandstaticmemberfunctionsofthesameclass.
Sandscoperesolution.5.2StaticMemberFunctionsExample:#include<iostream>spacestd;classPoint{public:Point(intxx=0,intyy=0){X=xx;Y=yy;countP++;}Point(Point&p);intGetX(){returnX;}intGetY(){returnY;}staticvoidGetC(){cout<<"Objectid="<<countP<<endl;}private:intX,Y;countP;}5.2StaticMemberFunctionsPoint::Point(Point&p){X=p.X;Y=p.Y;countP++;}intPoint::countP=0;voidmain(){PointA(4,5);cout<<"PointA,"<<A.GetX()<<","<<A.GetY();A.GetC();PointB(A);cout<<"PointB,"<<B.GetX()<<","<<B.GetY();Point::GetC();//andscoperesolution//usingobject}Chap.3ClassesandObjects6Const6Constant
Constant
Constantisjustlikeavariable,exceptthatitsvaluecannotbechanged.
Themodifierconstrepresentsaconstant.
constintx=10;
InC++,aconstmustalways
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026河南洛阳老城区南关社区卫生服务中心招聘备考题库及答案详解(名师系列)
- 2026浙江嘉兴高级中学编外用工招聘2人备考题库含答案详解(模拟题)
- 武汉市某水土保持站招聘水土保持监测员1名备考题库含答案详解(完整版)
- 2026浙江宁波市江北区劳动和社会保障事务代理服务有限公司招聘1人备考题库及答案详解(必刷)
- 2026江西省肿瘤医院高层次人才招聘29人备考题库(13)带答案详解ab卷
- 2026福建泉州石狮市蚶江镇中心幼儿园教师、保育员招聘备考题库含答案详解(培优a卷)
- 2026重庆国创投资管理有限公司招聘4人备考题库及答案详解(各地真题)
- 2026海南三亚市市场监督管理局上半年招聘下属事业单位工作人员1人备考题库(第1号)含答案详解(a卷)
- 2026江苏苏州市吴中区社会福利中心招聘护理员1人备考题库带答案详解(轻巧夺冠)
- 2026福建泉州经济技术开发区第二实验幼儿园合同教师招聘1人备考题库附答案详解
- 2025年70周岁以上老年人换长久驾照三力测试题库(附含答案)4
- GB/T 42968.9-2025集成电路电磁抗扰度测量第9部分:辐射抗扰度测量表面扫描法
- 湖南省新高考教学教研联盟2026届高三年级12月联考(长郡二十校联盟)数学试卷(含答案)
- 2024-2025学年度陕西能源职业技术学院单招《职业适应性测试》考试历年机考真题集(易错题)附答案详解
- 保安机具管理办法
- 一元二次方程综合测试(中考真题)(含答案)
- GB/T 25922-2023封闭管道中流体流量的测量用安装在充满流体的圆形截面管道中的涡街流量计测量流量
- 中国哲学简史-冯友兰(英文版)
- 人教版七年级上册数学第三章《一元一次方程》100题(含答案)
- 工程造价咨询报价单
评论
0/150
提交评论