面向对象的程序设计.ppt

上传人:sh****n 文档编号:7451337 上传时间:2020-03-21 格式:PPT 页数:47 大小:485KB
返回 下载 相关 举报
面向对象的程序设计.ppt_第1页
第1页 / 共47页
面向对象的程序设计.ppt_第2页
第2页 / 共47页
面向对象的程序设计.ppt_第3页
第3页 / 共47页
点击查看更多>>
资源描述
1 47 Object OrientedProgramming 计算机科学与技术学院刘培强liupq 2010 2011 01电信08计科09 2 47 Chapter2FromCtoC 2 1Namespaces2 2IntroductiontoC Input Output2 3Files2 4C Features2 5TheTypestring 3 47 2 1Namespaces 名字空间 4 46 Namespaces functions Anamespaceisascope C providesnamespacestopreventnameconflicts Example namespacemfc intinflag noclosingsemicolonrequirednamespaceowl intinflag noclosingsemicolonrequired 5 46 Namespaces functions Anamespaceisamechanismforexpressinglogicalgrouping Thatis ifsomedeclarationslogicallybelongtogethertosomecriteria 准则 theycanbeputinacommonnamespacetoexpressthatfact Thatis thenamespaceisthemechanismforsupportingmoduleprogrammingparadigm 范型 同一namespace中的声明在概念上属于同一个逻辑实体 6 46 Namespaces functions 7 46 Namespaces scoperesolutionoperator Thescoperesolutionoperator 域解析符 occursbetweenthenamespacesnameandthevariable mfc inflag 3 mfc sinflagowl inflag 823 owl sinflag 8 46 Namespaces usingdeclaration 由于各个namespace之间经常会出现互相使用对方成员的情况 如果一使用就要约束 既繁琐又容易出错 因此 C 提供了几种 有限的统一 约束的机制 Ausingdeclaration using声明 appliesasingleiteminthenamespace namespacemfc intinflag voidg int usingmfc inflag inflag 1 mfc g 6 9 46 Namespaces usingdirective Usingdirective using指示 isequivalenttoausingdeclarationforeachiteminanamespace Ausing directivemakesnamesfromanamespaceavailablealmostasiftheyhadbeendeclaredoutsidetheirnamespace usingnamespacemfc inflag 21 g 66 owl inflag 341 10 46 Namespaces usingdirective Anamespaceisascope Thus namespaceisaveryfundamentalandrelativelysimpleconcept Thelargeraprogramis themoreusefulnamespacesaretoexpresslogicalseparationsofitsparts Ideally 理想地 anamespaceshould 1 expressalogicallycoherent 相关的 setoffeatures 2 notgiveusersaccesstounrelatedfeatures and 3 notimposeasignificantnotationalburdenonusers 11 46 Namespaces std C sstdnamespacesincludesallofthestandardlibraries includeusingnamespacestd intmain cout C onesmallstepfortheprogram n onegiantleapfortheprogrammer n return0 12 47 2 2IntroductiontoC Input Output 13 46 C Input Outputbasicconcepts InC input outputistreatedasastreamofconsecutivebytes 连续的字节流 ThusC input outputiscalledstreaminput output 14 46 C Input Outputbasicconcepts TheheaderiostreammustbeincludedtouseC standardinput output cin thestandardinputobjectcout thestandardoutputobjectcerr thestandarderrorobject operator manipulator 操作符 usedforinput operator manipulatorusedforoutput 15 46 C Input Outputbasicconcepts operator and istoskipwhitespacebeforereadingthenextinputitem evenifthevariableisoftypechar 16 46 C Input Outputbasicconcepts includeusingnamespacestd intmain intval sum 0 cout val sum val cout Enternextnumber cout Sumofallvalues sum n return0 ifavalueisreadintoval cin valistrue otherwise false 17 46 C Input OutputManipulators Inputandoutputcanformattedusingmanipulators Exceptforsetw amanipulatorpermanentlychangesthestateofthestreamtowhichitisapplied TheManipulatorsaredividedintotwoclasses whicharewithargumentsorwithoutarguments Tousemanipulatorswithoutarguments theheaderiostreammustbeincluded Manipulatorswithargumentsrequiretheheaderiomanip Themanipulatoreffectlastsonlyforthenextinputoroutputoperation andoncethestatusofcoutischangedbyusingamanipulator otherthansetw thestatusremainsineffectuntilchangedagain 18 46 C Input OutputManipulators 19 46 C Input OutputManipulators 20 46 MixingCandC Input Output UsingtheCinput outputlibraryfunctionsandtheC classlibraryinthesameprogramcancauseproblemsbecausereadsandwritesfromthetwolibrariesarenotautomaticallysynchronized 同步 Ifthetwolibrariesaremixed thefunctionios sync with stdio shouldbeinvolvedbeforedoinganyinputoroutput 21 47 2 3Files 22 46 Files Theheaderfilefstreammustbeincludedtousefiles ifstream toreadfromafileofstream towritetoafile operator manipulatorusedtofileread operator manipulatorusedtofilewrite 23 46 Files includeusingnamespacestd constintcutoff 6000 constfloatrate1 0 3 constfloatrate2 0 6 intmain ifstreaminfile ofstreamoutfile intincome tax infile open income in outfile open tax out while infile income if income cutoff tax rate1 income elsetax rate2 income outfile Income income greenbacks n Tax tax greenbacks n infile close outfile close return0 Example2 3 1 Theprogramreadsincomesfromthefileincom inuntilend offileandwritestheincomeandtaxtothefiletax out 24 46 Files TestingWhetherFilesAreOpen Afteropeningafile itisagoodideatocheckwhetherthefilewassuccessfullyopened 25 46 Files TestingWhetherFilesAreOpen include includeusingnamespacestd constintcutoff 6000 constfloatrate1 0 3 constfloatrate2 0 6 intmain ifstreaminfile ofstreamoutfile intincome tax infile open income in if infile cerr Unabletoopenincom in n exit 0 outfile open tax out if outfile cerr Unabletoopentax out n exit 0 infile close outfile close return0 26 47 2 4C Features Casts 类型转换 Constants 常量 TheDataTypebool 布尔类型 EnumeratedTypes 枚举类型 Definingvariables 定义变量 Structures 结构 27 46 C Features Casts C addsfournewcasts static castconst castdynamic castreinterpret caststatic cast 一般的类型转换 Thecaststatic castisthemostcommonlyusedcast Itisusedtoconvertonedatatypetoanotherandhandlesall reasonable casts forexample convertinginttofloat Theothercastsarespecial purposecast Example intx 20 y 30 average float x float y theCcastingaverage static cast x static cast y theC casting 28 46 C Features Casts const cast 将常量转换成非常量 Asthenameimplies const castisusedtocastawayconstness Moreprecisely itisusedtocastapointertoaconstobjecttoapointertoanonconstobject Example includeusingnamespacestd constint find intval constint t intn functiondeclarationintmain inta 2 4 6 definearrayaandinitializethearrayint ptr ptrisapointertoint notice itisanonconstpointer ptr const cast find 4 a 3 typecastingif ptr 0 cout notfound endl elsecout found value ptr endl return0 constint find intval constint t intn intI for i 0 i n i if t i val return notfound 29 46 C Features Casts reinterpret cast 一种指针类型向另外一种指针类型的转换或整型向指针型的相互转换 Thecastreinterpret castisusedtoconvertapointerofonetypetoapointerofanothertype toconvertfromapointertypetoanintegertype andtoconvertanintegertypetopointertype Becausetheeffectisimplementationdependent reinterpret castshouldbeusedwithcaution Example intmain inti floatf 6 9072f unsignedchar p reinterpret cast 30 46 C Features Casts dynamic cast 运行时带有类型检测的类型转换 Thecastdynamic castisusedforcastingacrossorwithininheritancehierarchies Ex classB public virtualvoidf classD publicB public voidm intmain D p dynamic cast newB Error if p p m elsecerr NotsafeforptopointtoaB endl return0 31 46 C Features TheDataTypebool InC trueisrepresentedbynonzero andfalsebyzero C addedtheintegertypebooltorepresentthebooleanvaluestrueandfalse 布尔类型的名称 bool布尔类型的值集 true false 布尔类型的值可以承受算术 关系和逻辑运算 运算时 布尔类型的字面值 literal true和false分别被转换成 机器中 整数类型的值1和0 程序中的非零值代表true 0为false 32 46 C Features TheDataTypebool 布尔类型的主要用途 定义那些表达逻辑运算 logicaloperations 结果的变量 作为函数 用于测试某些条件 apredicate 的返回类型 voidf inta intb boolb1 a b boolis open File boolgreater inta intb returna b 33 46 C Features EnumeratedTypes Enumeration是用户以枚举值集的方式定义的类型 Enumeration值集中的每个值都是一个已命名的整数常量 Namedintegerconstant 这个名字就是Enumeration类型的一个字面值 枚举符 enumerator Noticethateveryenumerationisadistincttype 34 46 C Features EnumeratedTypes Enumeration类型的主要用途 是以易于理解 易于控制的方式表示程序中需要区分的状态 thatisgiveboththeuserandthecompilerahintastotheintendeduse 35 46 C Features EnumeratedTypes 一个Enumeration类型变量的取值范围为0 或 2n 1 2n 1 36 46 C Features Structures C hasmodifiedC sversionofstructures Inadditiontodatamembers inC astructcancontainfunctions 在C 中 结构被看成是一种特殊的类 以后详细介绍 37 47 2 5TheTypestring 38 46 TheTypestring C furnishes 提供 thetypestringasanalternativetoC snull terminatedarraysofchar Byusingstring theprogrammerdoesnothavetobeconcernedaboutstorageallocationorabouthandlingtheannoyingnullterminator 39 46 TheTypestring 40 46 TheTypestring erasemethod include includeusingnamespacestd intmain strings RayDennisSteckler s erase 4 7 从第4个字符开始连续删除7个字符cout s n s RaySteckler s erase 4 删除从第4个字符开始的所有字符cout s n s Ray return0 Thefunctioneraseremovesasubstringfromastring 41 46 TheTypestring insertmethod Thefunctioninsertinsertsastringatspecifiedposition include includeusingnamespacestd intmain strings1 RaySteckler strings2 Dennis s1 insert 4 s2 将字符串s2插入到字符串s1的第4个字符之后cout s1 n s1 RayDennisSteckler cout s2 n s2 Dennis return0 42 46 TheTypestring replacemethod Thefunctionreplacereplacesasubstringwithaspecifiedstring 43 46 TheTypestring replacemethod include includeusingnamespacestd intmain strings1 RayDennisSteckler strings2 Fran s1 replace 4 6 s2 用字符串s2替换字符串s1中从第4个字符 开始的连续6个字符cout s1 n s1 RayFranSteckler cout s2 n s2 Fran return0 44 46 TheTypestring swapmethod include includeusingnamespacestd intmain strings1 RayDennisSteckler strings2 Fran s1 swap s2 将字符串s1和字符串s2的值互换cout s1 n s1 Fran cout s2 n s2 RayDennisSteckler return0 45 46 TheTypestring findmethod Thefunctionfindisusedtosearchastringforasubstring include includeusingnamespacestd intmain strings1 RayDennisSteckler strings2 Dennis intf s1 find s2 字符串s1中是否出现了字符串s2if f s1 length cout Foundatindex f n elsecout Notfound n return0 46 46 Exercises P173P185 6P2410P314 5 47 47 NextLesson Chapter2 6Function
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 图纸专区 > 课件教案


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!