




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(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ǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 燒烤業(yè)網(wǎng)紅店區(qū)域代理合作協(xié)議范本
- 能源監(jiān)測(cè)數(shù)據(jù)實(shí)時(shí)采集與處理協(xié)議
- 社區(qū)共享廚房加盟店加盟店市場(chǎng)調(diào)研與競(jìng)爭(zhēng)分析協(xié)議
- 資產(chǎn)評(píng)估機(jī)構(gòu)合伙人合作協(xié)議及保密責(zé)任承諾書
- 建筑節(jié)能改造工程全過程審計(jì)監(jiān)管協(xié)議
- 2025年中國白皮杉醇行業(yè)市場(chǎng)規(guī)模調(diào)研及投資前景研究分析報(bào)告
- 生物農(nóng)藥田間試驗(yàn)技術(shù)支持與成果轉(zhuǎn)化協(xié)議
- 網(wǎng)絡(luò)數(shù)據(jù)恢復(fù)硬盤租賃與數(shù)據(jù)恢復(fù)技術(shù)培訓(xùn)合同
- 跨境電商平臺(tái)客服外包及售后服務(wù)合同
- 智能倉儲(chǔ)物流標(biāo)準(zhǔn)補(bǔ)充協(xié)議
- 安徽省六安市2024-2025學(xué)年八年級(jí)(下)期中歷史試卷(含答案)
- 航運(yùn)業(yè)人力資源開發(fā)與管理考核試卷
- 福建省三明市2025年普通高中高三畢業(yè)班五月質(zhì)量檢測(cè)物理試卷及答案(三明四檢)
- 7.1 觀察物體(課件)-2024-2025學(xué)年蘇教版數(shù)學(xué)一年級(jí)下冊(cè)
- 早產(chǎn)兒試題及答案多選
- 2025年上海市靜安區(qū)初三二模語文試卷(含答案)
- 2025年公共安全管理考試題及答案
- 2025年寧夏吳忠紅寺堡區(qū)公開招聘社區(qū)工作者46人筆試備考題庫及答案解析
- 搶救配合流程和站位規(guī)范
- 2025年高考物理考試易錯(cuò)題易錯(cuò)點(diǎn)07動(dòng)量定理、動(dòng)量守恒定律(3陷阱點(diǎn)7考點(diǎn)4題型)(學(xué)生版+解析)
- 雨季行車安全教育
評(píng)論
0/150
提交評(píng)論