C++面向对象程序设计双语教程(第3版)课件 class 5-classes objects-2、class 6-classes objects_第1页
C++面向对象程序设计双语教程(第3版)课件 class 5-classes objects-2、class 6-classes objects_第2页
C++面向对象程序设计双语教程(第3版)课件 class 5-classes objects-2、class 6-classes objects_第3页
C++面向对象程序设计双语教程(第3版)课件 class 5-classes objects-2、class 6-classes objects_第4页
C++面向对象程序设计双语教程(第3版)课件 class 5-classes objects-2、class 6-classes objects_第5页
已阅读5页,还剩53页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

ObjectivesToknowtheUMLdiagram-classdiagramBeawareoftheeffectofconstructorsanddestructorinaclassTobeabletodefineconstructorsanddestructorsandusethemTo

understandthedefinitionofaclassfurther01UMLDiagram04CaseStudy03Destructors02Constructors01UMLDiagramProblem-SolvingCase

Study

1DefineaDateclasswiththeday,monthandyear.Requirement:InputthedataofanobjectOutputthedataoftheobjectReset(modify)thedataoftheobjectGetthedayoftheobjectGetthemonthoftheobjectdataabstractionData:year,month,day-intFunctions(operations):inputoutputresetgetDaygetMonthcheckvoidinput()voidoutput()voidreset()intgetDay()intgetMonth()boolcheck()Problem-SolvingUsingUMLClassDiagramThe

UnifiedModelingLanguage(UML)isageneral-purposedevelopmental,modelinglanguageinthefieldofsoftwareengineeringthatisintendedtoprovideastandardwaytovisualizethedesignasystem.TheUMLdiagramisoftenusedforobject-orienteddesign.The

UML

classdiagramisagraphicalnotationusedtoconstructandvisualizeobjectorientedsystems.AclassdiagramintheUMLisatypeofstaticstructurediagramthatdescribesthestructureofasystembyshowingthesystem’s:classestheirattributes(datamembersinC++)operations/methods(memberfunctionsinC++)therelationshipsamongobjectsProblem-SolvingUsingUMLClassDiagramEncapsulationdataabstractionDate-day:int-month:int-year:int-check():bool+input():void+output():void+reset():void+getDay():int+getMonth():intdatamembers(properties)memberfunctions(Operations)UMLanalysisclass_nameaccessspecifier(-,+)datamemberaccessspecifier(-,+)memberfunctionsclassdiagramdataabstractionData:year,month,day-intFunctions(operations):inputoutputresetgetDaygetMonthcheckvoidinput()voidoutput()voidreset()intgetDay()intgetMonth()boolcheck()intmain(){Datetoday;today.input();today.output();today.reset();cout<<"theDateis"<<today.getMonth()<<"-"<<today.getDay();return0;}Implementationclass

Date{public:voidinput();voidoutput();voidreset();intgetDay();intgetMonth();private:intday,month,year;boolcheck();};Date-day:int-month:int-year:int-check():bool+input():void+output():void+reset():void+getDay():int+getMonth():intInformationhidingimplementationbool

Date::check(){if(day<1||day>31||month<1||month>12||year<1){ cout<<"Invaliddate!\n";return

false;}else return

true;}void

Date::reset(){cout<<"Resetadate\n";input();}int

Date::getMonth(){returnmonth;}int

Date::getDay(){returnday;}void

Date::output(){cout<<year<<"-"<<month<<"-"<<day<<endl;}Implementationvoid

Date::input(){do{cout<<"Entertheyear,monthanddayofadate:\n";cin>>year>>month>>day;}while(!check());}Date-day:int-month:int-year:int-check():bool+input():void+output():void+reset():void+getDay():int+getMonth():int02ConstructorsConstructorsintmain(){Datetoday;today.input();today.output();today.reset();cout<<"theDateis"<<today.getMonth()<<"-"<<today.getDay();return0;}Allocatememoryandinitializedatamembersvoid

Date::input(){do{cout<<"Entertheyear,monthanddayofadate:\n";cin>>year>>month>>day;}while(!check());}ConstructorWhotoallocatememory?Howmuchtoallocatememoryforobject?Howtostoredataofanobject?ConstructorsForexample,Datetoday;Aconstructorisaspecialmemberfunctionthatisautomaticallycalledwheneveraclassobjectiscreated.Aconstructorisrecognizedbyhavingthesamenameas

theclassitself.DefinitionofConstructorsMemberfunctionItsnameisthesameasclass’snameNoreturntypewithinitsdeclaration/definitionNoreturnstatementwithinitsdefinitionclass

Date{public:Date();voidoutput();voidreset();intgetDay();intgetMonth();private:intday,month,year;boolcheck();};constructorofclassDateDate::Date(){do{cout<<"Entertheyear,monthanddayofadate:\n";cin>>year>>month>>day;}while(!check());}Usageof

Constructorsintmain(){Datetoday;Datemybirthday;}classDate{public:Date();//..};Whenaclasshasaconstructor,allobjectsofthatclasswillbeinitializedbyaconstructorcall.OverloadingConstructorsThereareafewconstructorsinaclass.Constructorsobeythesameoverloadingrulesasdootherfunctions.Aslongastheconstructorsdiffersufficientlyintheirparametertypes,thecompilercanselectthecorrectoneforeachuse.

OverloadingConstructorsclassDate{public:

Date(int,int,int);Date(int,int);Date(int);Date();Date(const*char);private:intday,month,year;};intmain(){Datetoday(4);Datejuly4(“July42020”);Datenow;}AfewconstructorsinaclassaredefinedDefaultConstructorsDefaultconstructorsaredefinedinthethreeways.class

Date{public:Date();……intgetMonth();private:intday,month,year;boolcheck();};class

Date{public:Date(int=2020,int=9,int=1);……intgetMonth();private:intday,month,year;boolcheck();};DefaultconstructorDate::Date(){do{ cin>>year>>month>>day;}while(!check());}Date::Date(int

y,int

m,int

d){year=y;month=m;day=d;if(!check())exit(1);}3.Theconstructoriswithdefaultparameters;1.Theconstructorisnotdefinedintheclass;2.Theconstructoriswithoutparameters;class

Date{public:Date();Date(int=2020,int=9,int=1);……intgetMonth();private:intday,month,year;boolcheck();};intmain(){Datetoday(2015);Datetomorrow;return0;}//errorDefaultConstructorsWhenaclasshasmorethanonedefaultconstructor,thisleadstoambiguouscalltooverloadedconstructors.03DestructorsDestructors(析构函数)Adestructorisaspecialmemberfunctionthatisautomaticallyinvokedwheneveraclassobjectgoesoutofitsscope.Adestructorisrecognizedbyhavingthesameasthenameofitsclassprefixedbya~.

intmain(){Datetomorrow;return0;}Destructorsclass

Date{public:Date();……intgetMonth();~Date();private:intday,month,year;boolcheck();};destructorMemberfunctionItsnameisthesameasclass’snameprefixedbya~Noreturntypewithinitsdeclaration/definitionNoreturnstatementwithinitsdefinitionNoparameterswithinitsdefinitionDate::~Date(){cout<<"callingthedestructor\n";}intmain(){Datetomorrow;f();return0;}voidf(){Dateday;}OnlyonedestructorinaclassOrdersofConstructorandDestructorCallsAconstructorisimplicitlycalledwhenanobjectofaclassiscreated.Adestructorisimplicitlycalledwhenanobjectgoesoutofscope.Aconstructormakessurethatanobjectisproperlycreatedandinitialized.Conversely,adestructor

makessurethatanobjectisproperlycleanedupbeforeitisdestroyed.OrdersofConstructorandDestructorCallsclass

Date{public:Date(int=2020,int=9,int=1);voidoutput();~Date();private:intday,month,year;};Date::Date(int

y,int

m,int

d){cout<<"callingtheconstructor\n";year=y;month=m;day=d;}Date::~Date(){cout<<"callingthedestructor\n";output();}intmain(){Datetoday(2019);

Datetomorrow(2019,10,24);return0;}Outputresult:callingtheconstructorcallingtheconstructorcallingthedestructor2019-10-24callingthedestructor2020-9-1void

Date::output(){cout<<year<<"-"<<month<<"-"<<day<<endl;}Whentheobjectsarecreatedfromtoptodownin

a

scope,theconstructoriscalledinturn.Whentheobjectsgooutoftheirscope,thedestructorsarecalledinreverseorderofcreatingobjects.04CaseStudyCaseStudy-ProductSalesTotheissueofproductsale,youneedtodo:inputeachproduct'sID,unitprice,sales;(2)calculatetherevenueofallproducts;(3)printsaleinformation.YouanalysethisissuebyusingUMLandwriteoutabstracteddataandfunctions.DataabstractionData:foreachproduct,ID,price,sales–string,double,intforallproducts,datastructure-arrayFunction:Input–voidinput()Revenues–doublerevenues()Print–voidprint()UMLproduct_salesID[]:stringprice[]:doublesales[]:int+product_sales()+~product_sales()+input():void+revenues():double+print():voidCaseStudy-ProductSalesFilestructureProject:product.hproduct.cppprodouct-tets.cpp#include

<iostream>#include

<string>#include

<iomanip>using

namespacestd;const

intp_num=4;class

product_sales{public:product_sales();voidinput();doublerevenues();voidprint();~product_sales();private:stringID[p_num];doubleprice[p_num];intsales[p_num];};#include

"product.h"intmain(){product_salesfoodProduct;foodProduct.print();product_salesclothProduct;clothProduct.print();return0;}SummaryUMLdiagramconstructorsanddestructorinaclassDesignaclassObjectivesToabletodefineconstmemberfunctionsandconstobjectsTobeabletounderstandthethispointerToabletodefineandusestaticmembersTo

managedynamicmemorybyusingnewanddelete01ConstantMemberFunctionsandConstantObjects03StaticMembers02Thethispointers04FreeStore01ConstantMemberFunctionandConstantObjectsclass

Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;intgetMonth()const;~Date();private:intday,month,year;boolcheck();};ConstantMemberFunctionsConstantmemberfunctionsclass

Date{public:Date(int=2021,int=1,int=1);voidoutput();intgetDay();intgetMonth();~Date();private:intday,month,year;boolcheck();};int

Date::getMonth(){returnmonth;}int

Date::getDay(){returnday;}Definition:Usingkeywordconstdefinesconstantmemberfunctions.Theconstkeywordisplacedaftertheparameterlistinthe

functiondeclarationanddefinition.Thosefunctionsthatdonotmodifythedataofaclass,i.e.read-only,aredefinedasconstantmemberfunction.ConstantMemberFunctionsclass

Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;intgetMonth()const;~Date();private:intday,month,year;boolcheck();};int

Date::getMonth()const{returnmonth;}int

Date::getDay()const{returnday;}intmain(){Datetoday(2021,9,15);today.output();cout<<"Date:"<<today.getMonth()<<"-"<<today.getDay();return0;}int

Date::getMonth()const{

return++month;

}//errorConstantObjectsintmain(){Datetoday(2018,9,15);today.output();cout<<"Date:"<<today.getDay()<<endl;const

Dateday;//day.output();//errorcout<<"Date:"<<day.getDay()<<endl;return0;}constantobjectclass

Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;};Non-constantobjectAn

object

of

a

class

may

be

declaredtobeconst,justlikeanyotherC++variable.ConstantObjectsintmain(){Datetoday(2018,9,15);today.output();cout<<"Date:"<<today.getDay();const

Dateday;//day.output();//errorcout<<"Date:"<<day.getDay();return0;}Aconstmemberfunctioncanbeinvokedforbothconstantandnon-constantobjectsAnon-constmemberfunctioncanbeinvokedonlyfornon-constantobjectsTheconstpropertyofanobjectgoesintoeffectaftertheconstructorfinishesexecutingandendsbeforetheclass'sdestructorexecutes.Sotheconstructoranddestructorcanmodifythedatamembersoftheobject,butothermethods(i.e.functions)oftheclasscannot.02ThethisPointersThethisPointersThe

this

pointerisapointeraccessibleonlywithinthenon-staticmemberfunctionsofa

class.Thethispointerpointstotheobjectforwhichthefunctionwasinvoked.Butanobject’sthispointerisnotpartoftheobjectitself.thisisnotanordinaryvariablebecauseitisnon-modifiable-assignmentstothisarenotallowed.CaseStudy1:defineaDateclassThethisPointersvoid

Date::output(){cout<<

this->year<<

"-"

<<

this->month<<

"-"

<<

this->day<<endl;}class

Date{public:Date(int=2018,int=1,int=1);voidoutput();intgetDay()const;voidprintThis();private:intday,month,year;boolcheck();};void

Date::printThis(){cout<<

this

<<endl;}int

Date::getDay()const{return

this->day;}intmain(){Dateday1(2021,9,15);cout<<&day1<<endl;day1.printThis();cout<<

"Sizeoftheobject:"

<<

sizeof(day1)<<endl;Dateday2(2020,9,15);cout<<&day2<<endl;day2.printThis();cout<<

"Sizeoftheobject:"

<<

sizeof(day2)<<endl;return0;}001BFDC4001BFDC4Sizeoftheobject:12001BFDB0001BFDB0Sizeoftheobject:12ThethisPointersclass

Date{public:Date(int=2018,int=1,int=1);voidoutput();Date&reset(int,int,int);intgetDay()const;~Date();private:intday,month,year;boolcheck();};Date&Date::reset(int

y,int

m,int

d){this->year=y;this->month=m;this->day=d;return*this;}intmain(){Datetoday(2018,10,15);today.output();cout<<"Date:"<<(today.reset(2021,9,20)).getDay()<<endl;return0;}2018-10-15Date:20ObjectisdestroyedDate::~Date(){cout<<"Objectisdestroyed\n";}CaseStudy1-1:defineaDateclassRequirement:YouwillresetanewDatevaluebasedonthepreviousdefinitionofclassDateThethisPointerclass

Date{public:Date(int=2018,int=1,int=1);boolisEqual(Date&date);private:intday,month,year;boolcheck();};CaseStudy1-2:defineaDateclassRequirement:YoudeterminewhethertwoDateobjectsareequal.bool

Date::isEqual(Date&date){if(this->year==date.year&&this->month==date.month&&this->day==date.day)return

true;elsereturn

false;}intmain(){Dateday1(2021,9,15);Dateday2(2020,9,15);cout<<(day1.isEqual(day2)?"theyareequal":"theyareunequal")<<endl;return0;

}03StaticMembersStaticMembersDefineastudentclasswithastudentNodatamember.Youneedtodothefollowingtasks:OutputthedataofthestudentobjectsWorkoutthenumberofthestudentobjectsstudent-studentNo:int-count:int+student()+print():void+getCount():intCaseStudy2Dataabstraction:data:studentNo-intFunctionsPrint–voidprint()getCount-numberofstudentobjectsStaticMembersstudent::student()//constructor{count++;studentNo=count;}void

student::print(){cout<<

"studentNo:"

<<studentNo<<endl;}int

student::getCount(){

returncount;}intmain(){

studentst1;st1.print();cout<<st1.getCount()<<endl;

studentst2;st2.print();cout<<st2.getCount()<<endl;

studentst3;st3.print();cout<<st3.getCount()<<endl;

return0;}class

student{public:student();

voidprint();

intgetCount();private:

intcount=0;

intstudentNo=0;};Result:studentNo:11studentNo:11studentNo:11StaticMembersCountisnotdatamemberofthestudentclassintcount=0;class

student{public:student();

voidprint();

intgetCount();private:

intstudentNo=0;};student::student(){::count++;studentNo=::count;}void

student::print(){cout<<

"studentNo:"

<<studentNo<<endl;}int

student::getCount(){

return::count;}intmain(){

studentst1;st1.print();cout<<st1.getCount()<<endl;

studentst2;st2.print();cout<<st2.getCount()<<endl;

studentst3;st3.print();cout<<st3.getCount()<<endl;

return0;}studentNo:11studentNo:22studentNo:33StaticMembersclass

student{public:student();voidprint();private:intstudentNo=0;static

intcount;//thenumber};int

student::count=0;student::student(){count++;studentNo=count;}void

student::print(){cout<<"studentNo:"<<studentNo<<";count="<<count<<endl;}StaticdatamemberStaticdatamember’sinitialization:Mustbeplacedoutsidetheclass.intmain(){studentst1;st1.print();studentst2;st2.print();studentst3;st3.print();return0;}studentNo:1;count=1studentNo:2;count=2studentNo:3;count=3StaticMembersSt1StudentclassSt2St3countstudentNostudentNostudentNoStaticdatamember

isavariablethatispartofaclass,yetisnotpartofanobjectofthatclass.StaticMembersclass

student{public:student();//constructorvoidprint();private:intstudentNo=0;static

intcount;//thenumber};int

student::count=0;student::student()//constructor{count++;studentNo=count;cout<<

"count'saddress:"

<<&count<<endl;cout<<

"studentNo'saddress:"

<<&studentNo<<endl;}intmain(){

studentst1;cout<<

"st1'saddress:"

<<&st1

<<

"st1'ssize:"

<<

sizeof(st1)<<endl;studentst2;cout<<

"st2'saddress:"

<<&st2

<<

"st2'ssize:"

<<

sizeof(st2)<<endl;studentst3;cout<<

"st3'saddress:"

<<&st3

<<

"st3'ssize:"

<<

sizeof(st2)<<endl;return0;}count'saddress:0015D138studentNo'saddress:00EFFC90st1'saddress:00EFFC90st1'ssize:4count'saddress:0015D138studentNo'saddress:00EFFC84st2'saddress:00EFFC84st2'ssize:4count'saddress:0015D138studentNo'saddress:00EFFC78st3'saddress:00EFFC78st3'ssize:4StaticMemberFunctionsStaticmemberfunction

isafunctionthatneedsaccesstomembersofaclass,yetdoesnotneedtobeinvokedforaparticularobject.class

student{public:student();//constructorstatic

intgetCount();voidprint();private:intstudentNo;static

intcount;};Staticmemberfunctionint

student::count=0;student::student()//constructor{count++;studentNo=count;}void

student::print(){cout<<"studentNo:"<<studentNo<<endl;}int

student::getCount(){returncount;}StaticMember

Functionsclass

student{public:student();//constructorstatic

intgetCount();voidprint();private:intstudentNo;static

intcount;};Staticmemberfunctionint

student::count=0;student::student()//constructor{count++;studentNo=count;}void

student::print(){cout<<"studentNo:"<<studentNo<<endl;}int

student::getCount(){returncount;}intmain(){studentst1;st1.print();cout<<"studentnumberis"<<student::getCount()<<endl;studentst2;st2.print();cout<<"studentnumberis"<<student::getCount()<<endl;studentst3;st3.print();cout<<"studentnumberis"<<st3.getCount()<<endl;return0;}StaticMembersint

student::getCount(){studentNo++;//error:accesstonon-staticmember

returncount;//ok}Staticmemberfunctionsarenotattachedtoanyobject,thatis,theydonothavethispointer.Staticmemberfunctionscanonlyaccessstaticdatamembers.04FreeStoreFreeStoreLiteralconstdataStack(automaticstorage)Freestore(Heap)constantdataFunction’slocalvariables,arguments,returningdataandaddressPotentialavailablememoryGlobal(Staticdata)MemorylayoutGlobalandstaticvariablesintk1=1;intk2;static

intk3=2;static

intk4;intmain(){static

intm1=2,m2;inti=1;char*p;charstr[10]="hello";const

char*q="hello";p=(char*)malloc(100);free(p);return0;}FreeStore-dynamicmemoryAllmemoryneedsweredeterminedbeforeprogramexecutionbydefiningthevariableneeded.Buttheremaybecaseswherethememoryneedsofaprogramcanonlybedeterminedduringruntime.Whenthememoryneededdependonuserinput,

onthesecases,programsneedtodynamicallyallocateandfreememorybyusingnewanddeleteoperatorsinC++.FreeStore-dynamicmemory#include<typeinfo>intmain(){int*intp=new

int;*intp=20;int*intpt=new

int(8);cout<<ty

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论