![C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語(yǔ)教程(第3版)課件 class 1-Introduction-class 7-classes objects-4_第1頁(yè)](http://file4.renrendoc.com/view11/M00/10/0E/wKhkGWXUtiCASSFTAAHMK_sRCbw992.jpg)
![C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語(yǔ)教程(第3版)課件 class 1-Introduction-class 7-classes objects-4_第2頁(yè)](http://file4.renrendoc.com/view11/M00/10/0E/wKhkGWXUtiCASSFTAAHMK_sRCbw9922.jpg)
![C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語(yǔ)教程(第3版)課件 class 1-Introduction-class 7-classes objects-4_第3頁(yè)](http://file4.renrendoc.com/view11/M00/10/0E/wKhkGWXUtiCASSFTAAHMK_sRCbw9923.jpg)
![C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語(yǔ)教程(第3版)課件 class 1-Introduction-class 7-classes objects-4_第4頁(yè)](http://file4.renrendoc.com/view11/M00/10/0E/wKhkGWXUtiCASSFTAAHMK_sRCbw9924.jpg)
![C++面向?qū)ο蟪绦蛟O(shè)計(jì)雙語(yǔ)教程(第3版)課件 class 1-Introduction-class 7-classes objects-4_第5頁(yè)](http://file4.renrendoc.com/view11/M00/10/0E/wKhkGWXUtiCASSFTAAHMK_sRCbw9925.jpg)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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(維護(hù))–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. 本站所有資源如無(wú)特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(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è)招聘策略總結(jié)
- 2025年全球及中國(guó)螺旋藻蝦青素行業(yè)頭部企業(yè)市場(chǎng)占有率及排名調(diào)研報(bào)告
- 2025年全球及中國(guó)合成生物學(xué)智造平臺(tái)行業(yè)頭部企業(yè)市場(chǎng)占有率及排名調(diào)研報(bào)告
- 2025-2030全球輕型柴油發(fā)動(dòng)機(jī)行業(yè)調(diào)研及趨勢(shì)分析報(bào)告
- 2025-2030全球反流檢測(cè)設(shè)備行業(yè)調(diào)研及趨勢(shì)分析報(bào)告
- 2025-2030全球裝飾金屬板光纖激光切割機(jī)行業(yè)調(diào)研及趨勢(shì)分析報(bào)告
- 2025-2030全球降膜式風(fēng)冷螺旋式冷水機(jī)組行業(yè)調(diào)研及趨勢(shì)分析報(bào)告
- 2025年全球及中國(guó)無(wú)塑工業(yè)軟包涂層紙行業(yè)頭部企業(yè)市場(chǎng)占有率及排名調(diào)研報(bào)告
- 2025年全球及中國(guó)聚合物氫氣分離膜行業(yè)頭部企業(yè)市場(chǎng)占有率及排名調(diào)研報(bào)告
- 2025年全球及中國(guó)搖擺式生物工藝容器行業(yè)頭部企業(yè)市場(chǎng)占有率及排名調(diào)研報(bào)告
- 搞笑小品劇本《大城小事》臺(tái)詞完整版
- 物業(yè)服務(wù)和后勤運(yùn)輸保障服務(wù)總體服務(wù)方案
- 人大代表小組活動(dòng)計(jì)劃人大代表活動(dòng)方案
- 《大模型原理與技術(shù)》全套教學(xué)課件
- 2023年護(hù)理人員分層培訓(xùn)、考核計(jì)劃表
- 《銷售培訓(xùn)實(shí)例》課件
- 2025年四川省新高考八省適應(yīng)性聯(lián)考模擬演練(二)地理試卷(含答案詳解)
- 【經(jīng)典文獻(xiàn)】《矛盾論》全文
- Vue3系統(tǒng)入門與項(xiàng)目實(shí)戰(zhàn)
- 2024年寧夏回族自治區(qū)中考英語(yǔ)試題含解析
- 光伏發(fā)電項(xiàng)目試驗(yàn)檢測(cè)計(jì)劃
評(píng)論
0/150
提交評(píng)論