C++面向对象程序设计双语教程(第3版)课件全套 class 1-Introduction-class 14-template_第1页
C++面向对象程序设计双语教程(第3版)课件全套 class 1-Introduction-class 14-template_第2页
C++面向对象程序设计双语教程(第3版)课件全套 class 1-Introduction-class 14-template_第3页
C++面向对象程序设计双语教程(第3版)课件全套 class 1-Introduction-class 14-template_第4页
C++面向对象程序设计双语教程(第3版)课件全套 class 1-Introduction-class 14-template_第5页
已阅读5页,还剩397页未读 继续免费阅读

下载本文档

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

文档简介

ObjectivesTounderstandwhatacomputerprogrammingisToknowhowtowriteaprogramTorecognizetwoprogrammingmethodologies01HowtoWriteaProgram?02Two

ProgrammingMethodologies01HowtoWriteaProgram?WhatisProgramming?Problem(orTask):Abouta

student’sgradesRequirements:Astudentlearnstwocoursesatthisterm,thatis,OOP,math.Youneedtoinputtwogradesdisplaytwogradesdisplaymessagescondition:agrade<60,displaymessages“youfailedxxx”;otherwise,displaymessage“youpassedxxx”Calculatethesumoftwogradesandaverage,anddisplayresultsCaseStudy1ComputerProgramming–planningorschedulingtheperformanceofataskoraproblem,thatis,itisaprocessthatleadsfromoriginalcomputingproblemtoexecutablecomputerprogram.HowtoWriteaProgram?Phase1:Problem-solving-planningtheprocessoftask(1)Inputtwogrades;(2)Displaythesetwogrades;(3)Ifoneoftwogradesislessthan60,display“youfailedxxx”,otherwisedisplay“youpassedxxx”(4)Calculatethesumoftwogradesandaverage;(5)Displaytheresults.PseudocodeStep1.AnalysisandspecificationHowtoWriteaProgram?Step2.Generateanalgorithmbyusingaflowchart

gradeOfOPP<60yesnoinputgradeOfOPP,gradeOfMathoutputsum,averageStartEndgradeOfMath<60sum=gradeOfOPP+gradeOfMathoutputgradeOfOPP,gradeOfMathoutput“youpassedOPP”yesnooutput“youfailedOOP”output“youfailedMath”output“youpassedMath”average=sum/2Algorithm:astep-by-stepprocedureforsolvingaproblem.Step3.VerifyHowtoWriteaProgram?Step1.Youmightconsidersomequestionsinthecontextofprogramming.1.WhatdoIhavetoworkwith–thatis,whatismydata?gradeOfOOP,gradeOfMath,sum,average2.Whatdothedataitemslooklike?–data

types,int,double3.HowwillIknowwhenIhaveprocessedallthedata?–algorithm4.Howmanytimesistheprocessgoingtoberepeated?-structure5.Whatshouldmyoutput

looklike?6.Whatspecialerrors

mightcomeup?Phase2:Implementation–writeaprogramHowtoWriteaProgram?Step2.TranslatethealgorithmtoaprogramwithCStep3.Testtheprogram#include

<stdio.h>intmain(){intgradeOfOOP,gradeOfMath,sum;floataverage;scanf("%d%d",&gradeOfOOP,&gradeOfMath);printf("OOP:%dMath:%d\n",gradeOfOOP,gradeOfMath);if(gradeOfOOP<60) printf("youfailedOOP\n");else printf("youpassedOOP\n");if(gradeOfMath<60) printf("youfailedMath\n");else printf("youpassedMath\n");sum=gradeOfOOP+gradeOfMath;average=(float)sum/2;printf("sum%daverage%6.2f\n",sum,average);return0;}(1)Input:50,69(2)Input:85,55(3)Input:80,69HowtoWriteaProgram?Phase3:Maintenance(维护)–Modifytheprogramtomeetchangingrequirementsorcorrecterrors.#include

<stdio.h>intmain(){intgradeOfOOP,gradeOfMath,sum;floataverage;scanf("%d%d",&gradeOfOOP,&gradeOfMath);printf("OOP:%dMath:%d\n",gradeOfOOP,gradeOfMath);if(gradeOfOOP<60) printf("youfailedOOP\n");else printf("youpassedOOP\n");if(gradeOfMath<60) printf("youfailedMath\n");else printf("youpassedMath\n");sum=gradeOfOOP+gradeOfMath;average=(float)sum/2;printf("sum%daverage%6.2f\n",sum,average);return0;}Whaterrorsmightcomeup?

Formanystudents?Practice-orientedHowtoWriteaProgram?Phase1:Problem-solving:(1)analysisandspecification(2)generatesolution(algorithm)(3)verificationPhase2:Implementation:(1)concretesolution(writingprogram)(2)testPhase3:Maintenance:

(1)reuse

(2)maintainWritingaprogramhasthethree-phaseprocess02ProgrammingMethodologiesProgrammingMethodologies1.thestructuredprogramming(modular,procedural)e.g.C/C++,Pascal2.theobject-orientedprogramming(OOP)e.g.C++,Java,C#Abstractioniscrucialtobuildingthecomplexsoftwaresystems.Dataabstractioncanbesummedupasconcentratingontheaspectsrelevanttotheproblemandignoringthosethatarenotimportantatthemoment.DataAbstractionTwopopularmethodologiestoprogrammingStructuredProgrammingProblem:solveaquadraticequationDatavariables:a,b,c,root1,root2Datatype:float/doubleInputdata:a,b,cOutputdata:root1,root2Algorithm:

Problem-solvingCaseStudy2StructuredProgrammingImplementation#include

<stdio.h>#include

<math.h>intmain(){floata,b,c;floatroot1,root2;printf("Enterthevaluesofa,bandc:\n");scanf("%f%f%f",&a,&b,&c);if(fabs(a)<=1e-6||fabs(b)<=1e-6) printf("theequationhasnorealroots!\n");else{floatdisc=b*b-4*a*c;if(disc<0)printf("theequationhasnorealroots\n");if(disc==0){root1=root2=-b/(2*a);printf("therootis%6.2f",root1);}if(disc>0){root1=(-b+sqrt(disc))/(2*a);root2=(-b-sqrt(disc))/(2*a);printf("therootis%6.2fand%6.2f",root1,root2); }}return0;}StructuredProgramming#include

<stdio.h>#include

<math.h>>boolquadratic(float

a,float

b,float

c,float*root1,float*root2){if(fabs(a)<=1e-6||fabs(b)<=1e-6)return

false;else{floatdisc=b*b-4*a*c;if(disc<0)return

false;if(disc==0){*root1=*root2=-b/(2*a);return

true;}if(disc>0){*root1=(-b+sqrt(disc))/(2*a);*root2=(-b-sqrt(disc))/(2*a);return

true;}}}intmain(){float_a,_b,_c;float_root1,_root2;printf("Enterthevaluesofa,bandc:\n");scanf("%f%f%f",&_a,&_b,&_c);if(quadratic(_a,_b,_c,&_root1,&_root2))printf("therootsare%6.2fand%6.2f",_root1,_root2);elseprintf("theequationhasnorealroot.\n");return0;}Dividingaproblemintosmallersub-problemsiscalledstructureddesign.Thisprocessofimplementingastructureddesigniscalledstructuredprogramming.StructuredProgrammingStructuredProgrammingDividingaproblemintosmallersub-problems.Eachsub-problemisthenanalysed,andasolutionisobtainedtosolvethesub-problem.Thesolutionstoallsub-problemsarecombinedtosolvetheoverallproblem.Characteristics:Top-downdesign,stepwiserefinementandmodularprogrammingBenefit:improvingtheclarity,quality,anddevelopmenttimeofa

computerprogram.StructuredProgrammingquadratic(…){a,b,c,root1,root2}intmain(){……}(function)(function1)(function2)float_a,_b,_c,_root1,root2StructuredProgrammingProblem:Student’sgrades(1)Inputtwogrades;(2)Displaythesetwogrades;(3)Ifoneoftwogradesislessthan60,display“youfailedxxx”,otherwisedisplay“youpassedxxx”(4)Calculatethesumoftwogradesandaverage;(5)Displaytheresults.MainfunctionInputgradeoutputgradeDisplaypassMCalculationsum_averageoutputsum_averageCaseStudy1Object-OrientedProgramming(OOP)#include

<stdio.h>#include

<math.h>class

quadratic_equation{public:quadratic_equation(float

aa,float

bb,float

cc):a(aa),b(bb),c(cc){}boolquadratic(float*root1,float*root2){if(fabs(a)<=1e-6||fabs(b)<=1e-6)return

false;else{floatdisc=b*b-4*a*c;if(disc<0)return

false;if(disc==0){*root1=*root2=-b/(2*a);return

true;}if(disc>0){*root1=(-b+sqrt(disc))/(2*a);*root2=(-b-sqrt(disc))/(2*a);return

true;}}}private:floata,b,c;};class,auser-defineddatatypeintmain(){float_a,_b,_c;float_root1,_root2;printf("Enterthevaluesofa,bandc:\n");scanf("%f%f%f",&_a,&_b,&_c);quadratic_equationqe(_a,_b,_c);if(qe.quadratic(&_root1,&_root2))printf("therootsare%6.2fand%6.2f",_root1,_root2);elseprintf("theequationhasnorealroot.\n");return0;}Themethodofobjectqeintmain(){float_a,_b,_c;float_root1,_root2;printf("Enterthevaluesofa,bandc:\n");scanf("%f%f%f",&_a,&_b,&_c);if(quadratic(_a,_b,_c,&_root1,&_root2))printf("therootsare%6.2fand%6.2f",_root1,_root2);elseprintf("theequationhasnorealroot.\n");return0;}Usingobjectsandtheirinteractions(methods)todesignprogramsiscalledOOdesign.ThisprocessofimplementinganOOdesigniscalled

OOprogramming.ObjectsObject-OrientedProgramming(OOP)qe1qe2qe4qe3MainfunctionObject-OrientedProgramming(OOP)Object-orientedprogramming(OOP)isawidelyusedinthemain-streamprogrammingnowadays.Object-orientedprogrammingisaprogrammingparadigmthatuses“objects”whichcontaindataandoperations(methods).Thefirststepistoidentifythecomponentscalledobjects,whichformthebasisofthesolution,andtodeterminehowtheseobjectsinteractwithoneanother.Thenextstepistospecifyforeachobjecttherelevantdataandpossibleoperationstobeperformedonthedata.ProgrammingmethodCharacteristicsofOOPClass–user-definedtypeMethod–operations,functionsMessagepassingAbstraction–programmingprocessEncapsulation–singleunitInheritance–relationshipbetweenclassesPolymorphism-interfaceSummaryProgrammingisaprocessthatleadsfromoriginalcomputingproblemtoexecutablecomputerprogram.Howtowriteaprogram,havingthethree-phaseprocess,i.e.,problem-solving,implementationandmaintenance.TwopopularmethodologiestoprogrammingObjectivesTobeabletoconstructasimpleC++programTo

beabletobefamiliarwithinput/outputstreamToknowhowtouseC++constantsTounderstandhowtoconstructprogramsmodularlybyusingfunctions(data

abstraction)01C++ProgramStructure03Constants02Input/OutputStream04Functions01C++ProgramStructureABriefDescriptionofC++C++isageneral-purposeprogramminglanguagewithadvantagestowardsthesystemprogrammingthatisabetterCsupportsdataabstractionsupportsstructuredprogrammingsupportsobject-orientedprogrammingsupportsgenericprogrammingC++ProgramStructureProblem:Writeaprogramforagradebookofagivencourse.Thegradebookincludescourse’sname,hourandlecturer,aswellasstudent’sID,nameandgradeInputallinformationoncourseandstudent;Calculatetheaveragegradeofthecourse;Printthegradebook.CaseStudy1Requirements:C++ProgramStructureDataToacourse,name,hourandlecturer,averagegrade;Tomanystudents,ID,nameandgrade;2.Datatypesname,lecturer-string(char*),grade-int,average-float3.Outputagradebookhavingacoursename,hourandlecturer,manystudents’ID,nameandgrade,

and

course

average

grade.4.Procedures(algorithm)InputalldataincludeacourseandstudentsCalculateaveragegradePrintagradebookProblem-solvingIDNameGrade200405XXXwang89………average70.67Name:OOPHour:48Lecturer:LIUJMGradeBookofOOPC++ProgramStructuremainsetCoursesetStudentaverageGradeprintCourseprintStudentGradeprintGradeBookinputStructuredprogrammingC++ProgramStructure////////////////////////////////////////////////////////////////////////gradebook.cpp//Theprogramreadscourseinformationandstudents'gradefromthe//console,calculatestheaveragegradeandoutputsstudents'grades.//////////////////////////////////////////////////////////////////////#include

<iostream>#include

<string>#include

<iomanip>using

namespacestd;//declarationofconstantsconst

intstudentNum=5;//declarationofinputfunctionsvoidsetCourseInfo(string&cName,string&lectName,int&cHour);voidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],

int(&g)[studentNum]);doubleaverage(int

g[]);//declarationofoutputfunctionsvoidprintCourseInfor(string,string,int);voidprintGradeBook(int*,string*,int*);intmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);//DisplaythecourseandstudentdataprintCourseInfor(courseName,lecturer,courseHour);printGradeBook(studentNo,studentName,grade);return0;}C++ProgramStructuredoubleaverage(int

g[]){intsum=0;for(inti=0;i<studentNum;i++) sum+=g[i];return

static_cast<double>(sum)/studentNum;}C++ProgramStructure//ReadthecourseandstudentdatavoidsetCourseInfo(string&cName,string&lectName,int&cHour){cout<<"EntercourseInformation\n";cin>>cName>>lectName>>cHour;}voidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],

int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}C++ProgramStructurevoidprintCourseInfor(string

cName,string

lectName,int

cHour){cout<<"Coursename:"<<cName

<<"Coursehour:"<<cHour

<<"Lecturer:"<<lectName<<endl;}voidprintGradeBook(int*sNo,string*sName,int*sg){cout<<"----------------------------\n";cout<<"StudentNoNameGrade\n";for(inti=0;i<studentNum;i++)cout<<setw(9)<<right<<sNo[i]<<setw(10)<<sName[i]<<setw(7)<<right<<sg[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(sg)<<endl;}C++ProgramStructureAcommonstructureofsimple,onefile,C++programsCommentsdescribe

theprogram,name,…Includestatementsspecifytheheaderfilesforlibraries.//gradebook.cpp//Theprogramreadscourseinformation…Usingnamespacestatement.#include<iostream>usingnamespacestd;LinecommentsBlockcommentsGlobaldeclarations(consts,types,variables,...).const

intstudenNum=5;Functionprototypes(declarations)voidprintGradeBook(int*,string*,int*);The

mainfunctiondefinitionintmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);……}C++ProgramStructureFunctiondefinitionsdoubleaverage(int

g[]){intsum=0;for(inti=0;i<studentNum;i++) sum+=g[i];return

static_cast<double>(sum)/studentNum;}02Input/Output

Stream//ReadthestudentdatavoidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],

int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}Input/OutputStreamOutputstreamInputstreamTheiostreamlibrarydefinesinput/outputforeverybuilt-intype.#include<iostream>Input/OutputStreamAstream

isasequenceofcharactersfromthesourcetothedestination.Therearetwotypesofstreams:Inputstream:Asequenceofcharactersfromaninputdevice(keyboard)tothecomputer(variables).Outputstream:Asequenceofcharactersfromthecomputer(variables)toanoutputdevice(screen).Input/OutputStreamTheextractionoperator(>>)isusedasaninputoperator.Inputstreamisfromthedevicetovariables.Keyword

cinisthestandardinputstream.Theinsertionoperator(<<)isusedasoutputoperator.Outputstreamisfromvariablestothedevice.Keyword

coutisthestandardoutputstream.cin>>courseName>>courseHour>>lecturer;

cout<<“Coursename:“<<courseName<<endl;ConsoleinputConsoleoutput//ReadthestudentdatavoidsetGrade(int(&sNo)[studentNum],string(&sName)[studentNum],int(&g)[studentNum]){cout<<"Enterstudent'sgrades\n";for(inti=0;i<studentNum;i++){sNo[i]=i;cin>>sName[i]>>g[i];}}Input/OutputstreamOutputstream(printf)Inputstream(scanf)03ConstantsConstantsTheconst

keywordmeansthatavaluedoesnotchangedirectly.Aconstantmustbeinitialized.#include

<iostream>#include

<string>#include

<iomanip>using

namespacestd;//declarationofconstantsconst

intstudentNum=5;A#defineisamacrowhichreplacesthemacro-namewithauser-definedtextstatement.Aconstidentifierallowsavariabletobeconstantthroughoutthefile.Constantsconstintmodel=90;constintv[]={1,2,3,4};constintx;intmain(){model=200;v[2]++;}Example//error–cannotbechanged//error–cannotbechanged//error-don’tinitializevoidf(){charstr[]="hello";char*str1=str;const

char*p1=str;//valueisconstant//p1[2]='w';//errorp1=str1;char*constp2=str;//addressisconstantp2[2]='w';//p2=str1;//errorconst

char*constp3=str;//p3[2]='w';//error//p3=str1;//error}04FunctionsFunctionsintmain(){stringcourseName;stringlecturer;intcourseHour;intstudentNo[studentNum];stringstudentName[studentNum];intgrade[studentNum];//ReadthecourseandstudentdatasetCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);//DisplaythecourseandstudentdataprintCourseInfor(courseName,lecturer,courseHour);printGradeBook(studentNo,studentName,grade);return0;}Functions:programisbrief.easilymaintainenhancetheefficiencyofprogrammingreusableWhytousefunctions?Thefunctionalfeaturesofaprogramcanbesubdividedintoblocksofcodeknownas

functions.intmain(){…….setCourseInfo(courseName,lecturer,courseHour);}voidsetCourseInfo(string&cName,string&lectName,int&cHour){cout<<"EntercourseInformation\n";cin>>cName>>lectName>>cHour;}voidsetCourseInfo(string&cName,string&lectName,int&cHour);DeclarationandDefinitionofFunctionsAdeclarationestablishesthenameofthefunction,thetypeofreturnedbythefunction,theparameternumbersandtypesoftheparameterlist.declaration-prototypeFunctionbodyFunctiondefinitionFunctioncallHowtousefunctions?FunctionsignatureFunctionheaderFunctionswithDefaultArguments/ParametersProblem:Inquireastudent’sgradeinwhichispassorfail.intmain(){setCourseInfo(courseName,lecturer,courseHour);setGrade(studentNo,studentName,grade);inttempNo;cout<<"Inquireastudent'sgrade.EnterastudentID\n";cin>>tempNo;cout<<gradeResult(grade[tempNo])<<endl;return0;}chargradeResult(int,int=60);DefaultparameterchargradeResult(int

gradeOne,int

passValue){if(gradeOne>=passValue) return

'P';else return

'F';}DefaultargumentCaseStudy1-1FunctionswithDefaultParametersA

defaultparameterisafunctionparameter

thathasadefaultvalueprovidedtoit.chargradeResult(int,int=60);Adefaultparameteristypecheckedatthe

timeofthefunctiondeclarationandevaluatedatthetimeofthecall.(1)Iftheuserdoesnotsupplyavalueforthisparameter,thedefaultvaluewillbeused;(2)Iftheuserdoessupplyavalueforthedefaultparameter,theuser-suppliedvalueisusedinsteadofthedefaultvalue.FunctionswithDefaultParametersvoidprint(intval1=10,intval2=20,intval3=30);intmain(){print();print(31);print(31,10);print(31,16,15);}voidprint(intval1,intval2,intval3){cout<<val1<<val2<<val3<<endl;}Result:102030312030311030311615definitionFunctioncallWhentherecanexistmorethanoneparameterintheparameterlist,forexample,declarationLeftmostcriteria:fromlefttorightFunctionswithDefaultParametersvoidprint(intval1=10,intval2=20,intval3);voidprint(intval1=10,intval2,intval3=30);

voidprint(intval1,intval2=0,intval3=0);//error//error//okAlldefaultparameterswithindeclarationordefinitionmustbetherightmostparameters.Rightmostcriteria:fromrighttoleftFunction

OverloadingProblem:OutputthegradebookwithstudentIDandgrade.Twoormorefunctionshavethesamenameinthesamescopeiscalledfunctionoverloading.voidprintGradeBook(int*sNo,string*sName,int*sg);voidprintGradeBook(intsNo[],intg[]);C++allowsyoutospecifytwoormoredefinitionsfora

function

name

inthesamescope.Thecompilerwillneedtodeterminewhichfunctiontoexecutebasedonthefunctionsignature.Howtodo?CaseStudy1-2Function

OverloadingvoidprintGradeBook(int

sNo[],int

g[]){cout<<"----------------------------\n";cout<<"StudentNoGrade\n";for(inti=0;i<studentNum;i++) cout<<sNo[i]<<g[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(g)<<endl;}voidprintGradeBook(int*sNo,string*sName,int*sg){cout<<"----------------------------\n";cout<<"StudentNoNameGrade\n";for(inti=0;i<studentNum;i++) cout<<sNo[i]<<sName[i]<<sg[i]<<endl;cout<<"----------------------------\n";cout<<"Theaveragegrade:"<<average(sg)<<endl;}printGradeBook(studentNo,grade);printGradeBook(studentNo,studentName,grade);voidprintGradeBook(int*sNo,string*sName,int*sg);voidprintGradeBook(intsNo[],intg[]);Whenyoudefineoverloadedfunctions,youmustprovideaparameterlistwithdifferentparameters.Function

Overloading-HowtoCallanOverloadedFunctionMakingacalltoanoverloadingfunctionresultsinoneofthethreepossibleoutcomes:AmatchisfoundNomatchisfoundAnambiguousmatchisfoundFunction

Overloading–HowtoCallanOverloadedFunctionTrytofindanexactmatchTrytofindamatchthroughpromotions

booltoint

chartoint

e.g.charc=‘a’;

shorttoint

floattodoubleTrytofindamatchthroughstandardconversions

inttodouble

doubletointe.g.doublea=3.4;intn=(int)a;

doubletolongdoubleT*tovoid*

derived*toBase*

inttounsignedintCallingcriteriaWhenanoverloadedfunctioniscalled,asetofcriteriaaretriedtofindinorder:Function

Overloading-HowtoCallanOverloadedFunctionvoidprint(int);voidprint(char*)voidprint(double);voidprint(long);voidprint(char);voidh(charc,inti,shorts,floatf){print(c);print(i);print(s);print(f);print(‘a’);print(49);print(“a”);}//exactmatch//exactmatch//promotionmatch//promotionmatch//exactmatch//exactmatch//exactmatchFunction

Overloading–AmbiguousMatchDeclaringafewoverloadedfunctionscanleadtoambiguities.#include

<iostream>using

namespacestd;voidprint(double

d){cout<<

d

<<endl;}voidprint(long

l){cout<<

l

<<endl;}intmain(){print(1.0);//okprint(1L);//okprint(1);//errorreturn0;}datatypeambiguousmatchFunction

Overloading-AmbiguousMatch#include

<iostream>using

namespacestd;voidprint(double

d,double

f=1.0){cout<<

d

<<

f

<<endl;}voidprint(double

d){cout<<

d

<<endl;}intmain(){print(1,2);//okprint(10);//error-ambiguousargumentsreturn0;}Callafunctioncarefullywhendefaultparametersandfunctionoverloadingareinthesameprogram.SummaryC++programstructureInput/OutputstreamConstantsFunctionsDeclarationDefinitionDefaultparametersOverloadedfunctionObjectivesTounderstandthemechanismusedtopassinformationbetweenfunctionsTo

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(){

温馨提示

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

评论

0/150

提交评论