C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語教程(第3版)課件 class 3-basic facilities-2、class 4-classes objects_第1頁
C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語教程(第3版)課件 class 3-basic facilities-2、class 4-classes objects_第2頁
C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語教程(第3版)課件 class 3-basic facilities-2、class 4-classes objects_第3頁
C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語教程(第3版)課件 class 3-basic facilities-2、class 4-classes objects_第4頁
C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語教程(第3版)課件 class 3-basic facilities-2、class 4-classes objects_第5頁
已閱讀5頁,還剩51頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

ObjectivesTounderstandthemechanismusedtopassinformationbetweenfunctionsTo

beabletousereferencestopassargumentstofunctionsToknowhowthenamespaceworksout01ReviewPointers03Namespaces02References01ReviewPointersintmain(){intx;//Anormalintegerint*p=nullptr;//Declareapointertoanintegerp=&x;//Readit,"assigntheaddressofxtop"cout<<&x<<"|"<<&p<<endl;cin>>x;//Putavalueinxcout<<p<<"\t"<<*p<<"\n";cout<<x<<"\n";return0;}Pointers0012FF7C:x0012FF78:p0012FF7C7Notetheuseofthe*togetthevalueAvariablewhichstorestheaddressofanothervariableiscalleda

pointer.Pointershaveabasicdatatype,isreferredtoasacompoundtype.Pointersaresaidto“pointto”thevariablewhoseaddresstheystore.Result:0012FF7C|0012FF7870012FF7C77PointersPointersareaptlynamed:they“point”tolocationsinmemory.Pointersareanextremelypowerfulprogrammingtool.Pointerscanmakesomethingsmucheasier,helpimproveyourprogram‘sefficiency,andevenallowyoutohandleunlimitedamountsofdata.Pointersareoftendifficulttounderstand,andevenexperiencedprogrammersoftenfeelawfulbyerrorscausedbydebuggingpointers.PointersPointerscanrefereithertoamemoryaddressitself,ortoavariablethatstoresamemoryaddress.

Apointerisdeclaredinthefollowingcases:Ifyouwantavariablethatstoresamemoryaddressint*p;Ifavariablestorestheaddressofanothervariable,yousaythatitis“pointingto”thatvariable.

int*p=&x;Ifyoupassapointervariableintoafunction,you'repassingthevaluestoredinthepointer--thememoryaddress.voidf(int*p);Ifyouwanttomanipulateamemoryaddress,yourefertoitasamemoryaddress.intarr[]={2,3,4,5};int*p=arr;*++p;02ReferencesReferencesC++referencesallowyoutocreateasecondnameforavariablethatyoucanusetoreadormodifytheoriginaldatastoredinthatvariable.

A

reference

referstoanotherbasic

datatype,isreferredastoacompoundtype.A

reference

isanaliasoranalternativenameofavariable(anobject).intmain(){inti=10;int&r=i;}referenceSyntaxtodeclareareferencevariable:basictype&variableNameAreferencevariablemustbeinitializedMemoryResult:i1=5r=5&i1=0012FF7C&r=0012FF7C--------------------i1=8i2=8r=8&i1=0012FF7C&i2=0012FF70&r=0012FF7CReferencesintmain(){inti1;Int&r=i1;i1=5;cout<<"i1="<<i1<<endl;cout<<"r="<<r<<endl;cout<<"&i1="<<&i1<<endl;cout<<"&r="<<&r<<endl;inti2=8;r=i2;cout<<"i1="<<i1<<endl;cout<<"i2="<<i2<<endl;cout<<"r="<<r<<endl;cout<<"&i1="<<&i1<<endl;cout<<"&i2="<<&i2<<endl;cout<<"&r="<<&r<<endl;return0;}r0012FF7Ci1:50012FF70i2:88ReferencesandPointersintmain(){inti1=5;int&r=i1;//referenceint*ipt=&i1;//pointercout<<"&i1="<<&i1<<endl;cout<<"&r="<<&r<<endl;cout<<"*ipt="<<*ipt<<endl;cout<<“&ipt="<<&ipt<<endl;cout<<“ipt“<<ipt<<endl;

cout<<“-------------------\n”;inti2=8;ipt=&i2;cout<<"&i1="<<&i1<<endl;cout<<"&i2="<<&i2<<endl;cout<<"&r="<<&r<<endl;cout<<"*ipt="<<*ipt<<endl;cout<<“&ipt="<<&ipt<<endl;cout<<“ipt“<<ipt<<endl;}Result:&i1=0012FF7C&r=0012FF7C*ipt=5&ipt=0012FF74ipt=0012FF7C------------------------&i1=0012FF7C&i2=0012FF70&r=0012FF7C*ipt=8&ipt=0012FF74ipt=0012FF700012FF7C50012FF7C0012FF74i1:ipt:r80012FF70i2:0012FF70ReferencesTheaddressofareferenceistheaddressofthealiasedvariable.Itislesspowerfulbutsaferthanthe

pointer

typeinheritedfrom

C.CallingFunctionspass-by-valuepass-by-referencepass-by-pointervoidf(inta);voidf(int&a);voidf(int*a);Makingacalltoafunctionbyusingfollowingthreewaystopassarguments:CallingFunctionsbyValuesResult?Pass-by-valuevoidSwap(int

a,int

b){inttemp=a;a=b;b=temp;}intmain(){intaa=10,bb=20;Swap(aa,bb);cout<<aa<<bb;return0;}ab201020101020aabbmainSwapPass-by-value:Acopyofargument’svaluesismadeandpassedtocalledfunction.Changestothecopydonotaffecttheoriginalvaluesinthecaller.Thispreventstheaccidentalsideeffectsthatsogreatlyhinderthedevelopmentofcorrectandreliablesoftwaresystem.CallingFunctionsbyReferencesResult?voidSwap(int&a,int&b){inttemp=a;a=b;b=temp;}intmain(){intaa=10,bb=20;Swap(aa,bb);cout<<aa<<bb;return0;}1020aabbab2010Pass-by-reference:Thecallergivesthecalledfunctiontheabilitytoaccessthecaller’sdatadirectly,andtomodifythatdataifthecalledfunctionchoosestodoso.Pass-by-referenceCallingFunctionsbyPointersvoidSwap(int*a,int*b){inttemp=*a;*a=*b;*b=temp;}intmain(){intaa=10,bb=20;Swap(&aa,&bb);cout<<aa<<bb;return0;}Result?ab002EF950002EF9441020aabb002EF950002EF9442010Pass-by-pointer.Passingargumentstoafunctioncopiestheaddressofanargumentintotheformalparameter.Insidethefunction,theaddressisusedtoaccesstheactualargumentusedinthecall.Thismeansthatchangesmadetotheparameteraffectthepassedargument.Pass-by-pointerReturningValuesByReferences1.return-by-value

2.return-by-reference3.return-by-pointer

Returningavaluefromafunctioncanbeinthefollowingthreewaystoreturnavalue:intf(inta);int&f(int&a);int*f(int*a);ReturningValuesByReferencesintnValue;intreturnValue(int

n){nValue=n*2;

returnnValue;}int&returnReference(int

n){nValue=n*2;

returnnValue;}intmain(){intx=4;inti=returnValue(x);cout<<"i="<<i<<endl;i++;cout<<"nValue="<<nValue<<endl;int&j=returnReference(x);cout<<"j="<<j<<endl;j++;cout<<"nValue="<<nValue<<endl;return0;}Result:i=8nValue=8j=8nValue=9References

asLeft-handValueA

left-handvalue

isavalueontheleft-handsideofanassignmentoperation.jnValue38int&returnReference(int

n){nValue=n*2;

returnnValue;}intmain(){intx=4;int&j=returnReference(x);cout<<"j="<<j<<endl;j++;cout<<"nValue="<<nValue<<endl;intm=3;returnReference(x)=m;//left-handvaluecout<<"nValue="<<nValue<<endl;return0;}9Result:j=8nValue=9nValue=303NamespaceNamespacesAnamespaceisamechanismforexpressinglogicalgrouping,thatis,ifsomedeclarationslogicallybelongtogetheraccordingtosomecriteria,theycanbeputinacommonnamespacetoexpressthatfact.//my.h:charf(char);intf(int);

//your.hcharf(char);intf(int);

namespacemySpace{charf(char);intf(int);}

namespaceyourSpace{charf(char);intf(int);}Definitionnamespaceidentifier

{

oneentity

}SyntaxtodeclareanamespaceOnlyoneentitycanexistwithaparticularnameinaparticularscope.Namespaces1.Usingthescopeoperator(::)usingnamespacemySpace;usingnamespaceyourSpace;Namespacesallowustogroupnamedentitiesthatotherwisewouldhave

globalscope

intonarrowerscopes,givingthem

namespacescope.Thisallowsorganizingtheelementsofprogramsintodifferentlogicalscopesreferredtobynames.

namespacemySpace{charf(char);intf(int);}

namespaceyourSpace{charf(char);intf(int);}usagemySpace::f();yourSpace::f();2.UseusingstatementNamespacenamespacemySpace{inta=5;intb=6;}namespaceyourSpace{doublea=3.14;doubleb=5.67;}intmain(){usingmySpace::a;usingyourSpace::b;cout<<a<<endl;cout<<b<<endl;cout<<mySpace::b<<endl;cout<<yourSpace::a<<endl;return0;}Result:55.6763.14Namespaces#include<iostream>intmain(){inta;std::cin>>a;std::cout<<

"a="

<<a<<std::endl;return0;}#include<iostream>using

namespacestd;intmain(){inta;cin>>a;cout<<

"a="

<<a<<endl;return0;}SummaryTwo

compound

types

referencesandpointersReferencesaaliasnamereferencesasparametersoffunctionsreferencesasreturningvaluesoffunctionsReferencesasaleft-handvalueNamespaceObjectivesTounderstanddataabstractionfurtherTobeabletoknowwhataclassisandhowtocreateanobjectTo

understandencapsulationandinformationhiding01IntroductiontoStructures03Classesand

Objects02DataAbstraction04AccessControl05EncapsulationandInformationHiding01IntroductiontoStructureIntroductiontoStructuresCase

Study

1Problem:Writeaprogramforagradebookofagivencourse.Agradebookincludescourse’sname,student’sIDandgrade;Inputallinformationoncourseandstudent;Calculatetheaveragegradeofthecourse;Printthegradebook.Requirements:DatastructureA

datastructure

isagroupofdataelementsgroupedtogetherunderonename.structgradeBook{stringcourseName;stringstudentID;intstudentGrade;};Datatypes:built-intypes,e.g.int,char,floatandsoon.IntroductiontoStructuresinCstruct

gradeBook{stringcourseName;stringstudentID[studentNum];intstudentGrade[studentNum];};voidinput(gradeBook&oop);doubleaverage(gradeBook&oop);voidprint(gradeBook&oop);intmain(){gradeBookgbOOP;input(gbOOP);print(gbOOP);return0;}adatatype,auser-definedtypeMembersAstructuretypeisanaggregationofdifferentdatatypesunderonename.Dotoperator(.)Arrowoperator(->)Memberaccessoperatorsvoidinput(gradeBook&oop){cin>>

oop.courseName;for(inti=0;i<studentNum;i++)cin>>

oop.studentID[i]>>

oop.studentGrade[i];}IntroductiontoStructuresinC++struct

gradeBook{stringcourseName;stringstudentID[studentNum];intstudentGrade[studentNum];voidinput(){cin>>courseName;for(inti=0;i<studentNum;i++)cin>>studentID[i]>>studentGrade[i];}doubleaverage(){intsum=0;for(inti=0;i<studentNum;i++)sum+=studentGrade[i];return(double)sum/studentNum;}voidprint(){cout<<

"coursename:"

<<courseName<<endl;for(inti=0;i<studentNum;i++)cout<<studentID[i]<<

"|"

<<studentGrade[i]<<endl;cout<<

"course'saverage:"

<<average()<<endl;}};intmain(){gradeBookgbOOP;gbOOP.input();gbOOP.print();return0;}MemberfunctionsData

membersMembersStructurewithmemberfunctionsIntroductiontoStructureinC++struct

gradeBook{stringcourseName;stringstudentID[studentNum];intstudentGrade[studentNum]={0};voidinput();doubleaverage();voidprint();};intmain(){gradeBookgbOOP;gbOOP.input();gbOOP.print();return0;}void

gradeBook::input(){cin>>courseName;for(inti=0;i<studentNum;i++)cin>>studentID[i]>>studentGrade[i];}double

gradeBook::average(){intsum=0;for(inti=0;i<studentNum;i++)sum+=studentGrade[i];return(double)sum/studentNum;}C++11:InitializerinthestructureDefiningaStructureinCCase

Study

2Problem:WriteaprogramofaDatetype.Adateincludesyear,month,day;Inputallinformationonadate;Printthedate.Requirements:struct

Date{intyear,month,day;};intmain(){Datetoday,d[2];//arraycin>>today.year>>today.month>>today.day;cout<<today.year<<endl;cin>>d[0].year>>d[0].month>>d[0].day;cin>>d[1].year>>d[1].month>>d[1].day;cout<<d[1].year<<d[1].month<<d[1].day<<endl;Date*dptr=&today;//pointerdptr->year=2010;cout<<dptr->year<<dptr->month<<dptr->day<<endl;Date&rd=today;//referencecout<<rd.year<<rd.month<<rd.day<<endl;return0;}Dotoperator(.)Arrowoperator(->)MemberaccessoperatorsDefiningaStructureinCstruct

Date{ intyear,month,day;};voidinput_date(Date&date,int

y,int

m,int

d){date.year=y;date.month=m;date.day=d;}voidprint_date(Date&date){cout<<date.year<<date.month<<date.day<<endl;}intmain(){Datetoday;input_date(today,2017,10,1);print_date(today);return0;}DefiningaStructureinC++struct

Date{intyear,month,day;voidinput_date(inty,intm,intd);voidprint_date();};void

Date::input_date(int

y,int

m,int

d){year=y;month=m;day=d;}void

Date::print_date(){cout<<year<<month<<day<<endl;}intmain(){Datetoday;today.input_date(2016,10,12);today.print_date();return0;}Memberfunctions02DataAbstractionDataAbstractionLogicalpropertiesofthegradeBook,Datestructuredtypes:Threemembervariables,e.g.courseName,studentID,studentGrade,year,month,dayDeclarationoffunctions,e.g.input,average,print,input_date,print_date,…Implementation:DefinitionoffunctionsDataabstractionisdefinedasaprocessofseparatingthelogicalpropertiesofdatafromitsimplementationdetail.Dateabstractionisusedasamethodinanobject-orientedprogramming.AbstractDataTypesDefinitionofaDateADTdataTypeNamegradeBook,DateDomaineachdatatyperepresentsvalues,e.g.courseName,studentID,studentGrade,year,month,dayOperationsInputtheinformationofcourseandstudentsPrintagradebookinputadateprintadateAbstractdatatype(ADT)Adatatypeseparatesthelogicalpropertiesfromtheimplementationdetail.03ClassesandObjectsClassesandObjectsprint_dateinput_dateyear,month,daydateClasses

areanexpandedconceptof

datastructures:likedatastructures,theycancontaindatamembers,buttheycanalsocontainfunctionsasmembers.Classisauser-definedtypeinaprogramminglanguagethatisusedtorepresentanabstractdatatype(ADT).Aclassisasetorcollectionofabstractedobjectsthatsharecommoncharacteristics.printinputcourseName,studentIDstudentGradegradeBookDefinitionofaClassclassDate{

private:

intday;

intmonth;

intyear;

public:

voidinput_date(intd,intm,inty);

voidprint_date();};datamembermemberfunctionsaccesscontrolspecifierClassnameclassclass_name

{accesscontrolspecifier:datamembers;memberfunctions;};Syntaxtodeclareaclasstype

Thecomponentsofaclassarecalledthemembersoftheclass.Themembersoftheclassmaybeeitherdatatypeorfunctions.Dataintheclassarecalleddatamembers.Functionsdeclaredwithintheclassdefinitionarecalledmemberfunctions.DefinitionofaClassconst

intstudentNum=3;class

gradeBook{public:voidinput();doubleaverage();voidprint();private:stringcourseName="";stringstudentID[studentNum]={""};intstudentGrade[studentNum]={0};};memberfunctionsdatamemberClassnameaccesscontrolspecifierDefininganObjectDatemy_birthday;objectDeclarelocalobjectse.g.inanyfunctionDeclareglobalobjectsDeclareobjectsasclassmembersDeclareanobjectarraye.g.Dateday[10];Declareconstantobjectse.g.constDatedayDeclareobjectreferencesorpointerse.g.Date*pDay;Declarestaticobjecte.g.staticDatedayWhenaclassisused,anobjectisdeclared.Date*today;Dated1[3];ConceptofanobjectAnobject

isavariableofaclasstype,orclassinstance.Whenisanobjectdeclared?Inwhichwayisanobjectdeclared?Anobjectisdeclaredinthesameasbuilt-inttypesintmain(){Datetoday;today.input_date(2016,10,12);today.print_date();return0;}HowtoAccessMemberFunctionsinaClassMemberfunctionswithinaclasscanbeinvokedbyaclassvariable(i.e.object).objectaccessingmemberfunctionclassDate{

private:

intday;

intmonth;

intyear;

public:

voidinput_date(intd,intm,inty);

voidprint_date();};DefinitionofMemberFunctionsclass

Date{private:intday,month,year;public:voidinput_date(int

d,int

m,int

y){ day=d;month=m;year=y;}voidadd_year(int

n){year+=n;}voidadd_month(int

n){month+=n;}voidadd_day(int

n){day+=n;}};class

Date{private:intday,month,year;public:voidinput_date(int

d,int

m,int

y);voidadd_year(int

n);voidadd_month(int

n);voidadd_day(int

n);};inline

void

Date::add_year(n){year+=n;}inlinevoidadd_month(int

n){month+=n;}inlinevoidadd_day(int

n){day+=n;}DefinememberfunctionswithinaclassTheinlinefunctionsinstructcompilertoinsertcompletebodyofthefunctionwhereverthatfunctiongotusedincode.intmain(){Dateday;day.input_date(9,8,2020);day.add_year(1);return0;}DefinitionofMemberFunctionsBecausedifferentclassescanhavememberfunctionswiththesamename,wemustspecifytheclassnamewhendefiningamemberfunction.DefinememberfunctionsoutsidetheClassclass

Date{private:intday,month,year;public:voidinput_date(int

d,int

m,int

y);voidadd_year(int

n);voidadd_month(int

n);voidadd_day(int

n);};void

Date::input_date(int

d,int

m,int

y){day=d;month=m;year=y;}void

Date::add_year(n){year+=n;}void

Date::add_month(int

n){month+=n;}voidadd_day(int

n)//error{day+=n;}DefinitionofMemberFunctionsDefinememberfunctionsoutsidetheClassconst

intstudentNum=3;class

gradeBook{public:voidinput();doubleaverage();voidprint();private:stringcourseName="";stringstudentID[studentNum]={""};intstudentGrade[studentNum]={0};};void

gradeBook::input(){cin>>courseName;for(inti=0;i<studentNum;i++)cin>>studentID[i]>>studentGrade[i];}double

gradeBook::average(){intsum=0;for(inti=0;i<studentNum;i++)sum+=studentGrade[i];return(double)sum/studentNum;}void

gradeBook::print(){cout<<

"coursename:"

<<courseName<<endl;for(inti=0;i<studentNum;i++){ cout<<setw(9)<<right<<studentID[i]

<<setw(7)<<right<<studentGrade[i]<<endl;}cout<<

"----------------------------\n";cout<<

"Theaveragegrade:"

<<average()<<endl;}04AccessControlAccessControlclass

Date{private:intday,month,year;public:voidinput_date(int

d,int

m,int

y);voidadd_year(int

n);voidadd_month(int

n);voidadd_day(int

n);};accessspecifierAccesscontrol

isenforcedatcompiletime,notatrun-time.Whenamemberisaccessed,thecompilercheckstheaccessspecifierforit.Anaccessspecifierisoneofthreekeywords:private,publicorprotectedclass

Date{intday,month,year;public:voidinput_date(int

d,int

m,int

y);voidadd_year(int

n);voidadd_month(int

n);voidadd_day(int

n);};class

Date{public:voidinput_date(int

d,int

m,int

y);voidadd_year(int

n);voidadd_month(int

n);voidadd_day(int

n);private:intday,month,year;};class

Date{public:voidinput_date(int

d,int

m,int

y);private:voidadd_year(int

溫馨提示

  • 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ì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論