版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
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(chǎn)’;
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(chǎn)’);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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度產(chǎn)學研合作項目研發(fā)成果轉(zhuǎn)化與知識產(chǎn)權保護協(xié)議4篇
- 2024版軟件源碼授權保密協(xié)議范本
- 二手房私人交易協(xié)議模板2024版B版
- 2025年度新能源電池研發(fā)與采購安裝合同范本3篇
- 2025年度廠房修建與綠色建筑節(jié)能檢測服務合同4篇
- 2025年度智慧城市建設規(guī)劃與實施合同4篇
- 2025年度地理信息數(shù)據(jù)庫建設測繪合同4篇
- 2025年度企業(yè)培訓中心場地租賃及課程開發(fā)服務合同3篇
- 二零二五年度傳統(tǒng)煙酒品牌傳承保護協(xié)議
- 二零二五年度研學旅行安全保障及責任劃分合同
- 銀行2025年紀檢工作計劃
- 2024-2024年上海市高考英語試題及答案
- 注射泵管理規(guī)范及工作原理
- 山東省濟南市2023-2024學年高二上學期期末考試化學試題 附答案
- 大唐電廠采購合同范例
- 國潮風中國風2025蛇年大吉蛇年模板
- GB/T 18724-2024印刷技術印刷品與印刷油墨耐各種試劑性的測定
- IEC 62368-1標準解讀-中文
- 15J403-1-樓梯欄桿欄板(一)
- 2024年中考語文名句名篇默寫分類匯編(解析版全國)
- 新煤礦防治水細則解讀
評論
0/150
提交評論