C++面向?qū)ο蟪绦蛟O計雙語教程(第3版)課件 class 2-basic facilities-1_第1頁
C++面向?qū)ο蟪绦蛟O計雙語教程(第3版)課件 class 2-basic facilities-1_第2頁
C++面向?qū)ο蟪绦蛟O計雙語教程(第3版)課件 class 2-basic facilities-1_第3頁
C++面向?qū)ο蟪绦蛟O計雙語教程(第3版)課件 class 2-basic facilities-1_第4頁
C++面向?qū)ο蟪绦蛟O計雙語教程(第3版)課件 class 2-basic facilities-1_第5頁
已閱讀5頁,還剩31頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

ObjectivesTobeabletoconstructasimpleC++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*

inttounsigned

溫馨提示

  • 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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論