C++计算机语言教学课件c++-lect04classes-and-data-abstractioni_第1页
C++计算机语言教学课件c++-lect04classes-and-data-abstractioni_第2页
C++计算机语言教学课件c++-lect04classes-and-data-abstractioni_第3页
C++计算机语言教学课件c++-lect04classes-and-data-abstractioni_第4页
C++计算机语言教学课件c++-lect04classes-and-data-abstractioni_第5页
已阅读5页,还剩42页未读 继续免费阅读

付费下载

下载本文档

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

文档简介

Chapter3:ClassesandDataAbstraction(II)

Outline3.7 InitializingClassObjects:Constructors3.8 UsingDefaultArgumentswithConstructors3.9 UsingDestructors3.10 WhenConstructorsandDestructorsAreCalled3.11 UsingDataMembersandMemberFunctions3.12 ASubtleTrap:ReturningaReferencetoaprivate Data Member3.13 AssignmentbyDefaultMemberwiseCopy3.14 SoftwareReusabilityObjectivesInthischapter,youwilllearn:Tounderstandhowtocreate,use,anddestroyclassobjects.Tobeabletocontrolaccesstoobjectdatamembersandmemberfunctions.Tobegintoappreciatethevalueofobjectorientation.3.7InitializingClassObjects:Constructors(I)Constructor

functionCaninitializeclassmembersSamenameastheclass,noreturntypeMembervariablescanbeinitializedbytheconstructororsetafterwardsDefiningobjectsInitializerscanbeprovidedInitializerspassedasargumentstotheclass’constructor3.7InitializingClassObjects:Constructors(II)Format TypeObjectName(

value1,value2,…);Constructorassignsvalue1,value2,etc.toitsmembervariablesIfnotenoughvaluesspecified,rightmostparameterssettotheirdefault(specifiedbyprogrammer)

myClassmyObject(3,4.0);3.8UsingDefaultArgumentswithConstructorsDefaultconstructorOneperclassCanbeinvokedwithoutargumentsCanbesetwithdefaultargumentsDefaultarguments(缺省参数需要在函数声明的时候写上)Setindefaultconstructorfunctionprototype(inclassdefinition)Donotsetdefaultsinthefunctiondefinition,outsideofaclassExample:SampleClass(int=0,float=0);Constructorhassamenameasclasstime2.htime2.cpp(Part1of2)time2.cpp(Part2of2)fig16_07.cpp(Part1of2)fig16_07.cpp(Part2of2)Constructedwith:allargumentsdefaulted:00:0012:00:00AMhourspecified;minuteandseconddefaulted:02:002:00:00AMhourandminutespecified;seconddefaulted:21:349:34:00PMhour,minute,andsecondspecified:12:2512:25:42PMallinvalidvaluesspecified:00:0012:00:00AMProgramOutput3.9UsingDestructorsDestructor

MemberfunctionofclassPerformsterminationhousekeepingbeforethesystemreclaimstheobject’smemoryComplementoftheconstructorNameistilde(~)followedbytheclassname~TimeRecallthattheconstructor’snameistheclassnameReceivesnoparameters,returnsnovalue(无形参定义)Onedestructorperclass-nooverloadingallowed3.9UsingDestructors析构函数在对象生命周期结束时,回收其所占用的内存空间。析构函数是“反向”的构造函数,析构函数不允许有返回值,不带参数,一个类中只有一个。析构函数的作用正好与构造函数相反。当对象超出其作用范围,对应的内存空间被系统回收或被程序用delete删除时,析构函数将被调用。3.10WhenConstructorsandDestructorsAreCalled(I)ConstructorsanddestructorscalledautomaticallyOrderdependsonscopeofobjectsGlobalscopeobjects(在main函数外声明的变量)Constructorscalledbeforeanyotherfunction(includingmain)Destructorscalledwhenmainterminates(orexitfunctioncalled)

Destructorsnotcalledifprogramterminateswithabort3.10WhenConstructorsandDestructorsAreCalled(II)Automaticlocalobjects

ConstructorscalledwhenobjectsdefinedDestructorscalledwhenobjectsleavescope(whentheblockinwhichtheyaredefinedisexited)DestructorsnotcalledifprogramendswithexitorabortstaticlocalobjectsConstructorscalledwhenexecutionreachesthepointwheretheobjectsaredefinedDestructorscalledwhenmainterminatesortheexitfunctioniscalledDestructorsnotcallediftheprogramendswithabortcreate.hcreate.cppfig16_08.cpp(Part1of2)fig16_08.cpp(Part2of2)Object1constructor(globalcreatedbeforemain)Object2constructor(localautomaticinmain)Object3constructor(localstaticinmain)Object5constructor(localautomaticincreate)Object6constructor(localstaticincreate)Object7constructor(localautomaticincreate)Object7destructorObject5destructorObject4constructor(localautomaticinmain)Object4destructorObject2destructorObject6destructorObject3destructorObject1destructorProgramOutput3.11UsingDataMembersandMemberFunctionsClassesprovidepublicmemberfunctions

Set(i.e.,write)orget(i.e.,read)valuesofprivatedatamembersE.g.,oneactiontooperatetheprivatedatamembersofclassNamingMemberfunctionthatsetsinterestRatetypicallynamedsetInterestRateMemberfunctionthatgetsinterestRate

wouldtypicallybecalledgetInterestRate3.11UsingDataMembersandMemberFunctions(II)Dosetandgetcapabilitieseffectivelymakedatamemberspublic?No!ProgrammerdecideswhatthefunctioncansetandwhatinformationthefunctioncangetpublicsetfunctionsshouldCheckattemptstomodifydatamembersEnsurethatthenewvalueisappropriateforthatdataitemExample:anattempttosetthedayofthemonthto37wouldberejectedProgrammermustincludethesefeaturestime3.h(Part1of2)time3.h(Part2of2)time3.cpp(Part1of3)time3.cpp(Part2of3)time3.cpp(Part3of3)fig16_09.cpp(Part1of3)fig16_09.cpp(Part2of3)fig16_09.cpp(Part3of3)

Resultofsettingallvalidvalues:Hour:17Minute:34Second:25

Resultofattemptingtosetinvalidhourandsecond:

Hour:0Minute:43Second:0Incrementingminute3times:Starttime:11:58:00AMminute+1:11:59:00AMminute+1:12:00:00PMminute+1:12:01:00PMProgramOutput3.12ASubtleTrap:ReturningaReferenceto

aPrivateDataMemberReferencetoanobjectAliasforthenameoftheobjectCanbeusedontheleftsideofanassignmentstatementReferencecanreceiveavalue,whichchangestheoriginalobjectaswellOnewaytousethiscapabilityHaveapublicmemberfunctionofaclassreturnanon-constreferencetoaprivatedatamemberThisreferencecanbemodified,whichchangestheoriginaldatatime4.htime4.cpp(Part1of2)time4.cpp(Part2of2)fig16_10.cpp(Part1of2)fig16_10.cpp(Part2of2)

ProgramOutputHourbeforemodification:20Houraftermodification:30

*********************************POORPROGRAMMINGPRACTICE!!!!!!!!badSetHourasanlvalue,Hour:74*********************************3.13AssignmentbyDefaultMemberwiseCopyAssignmentoperator(=)Setsvariablesequal,i.e.,x=y;CanbeusedtoassignanobjecttoanotherobjectofthesametypeMemberwisecopy—memberbymembercopy

myObject1=myObject2;Objectsmaybe(willbeintroducedlater)PassedasfunctionargumentsReturnedfromfunctions(call-by-valuedefault)Usepointersforcallbyreferencefig16_11.cpp(Part1of2)fig16_11.cpp(Part2of2)

date1=7-4-1993date2=1-1-1990

Afterdefaultmemberwisecopy,date2=7-4-1993ProgramOutput3.14SoftwareReusabilityObject-orientedprogrammers

ConcentrateonimplementingusefulclassesTremendousopportunitytocaptureandcatalogclassesAccessedbylargesegmentsoftheprogrammingcommunity

Classlibraries

existforthispurposeSoftwareConstructedfromexisting,well-defined,carefullytested,portable,widelyavailablecomponentsSpeedsdevelopmentofpowerful,high-qualitysoftwarenamespace(命名空间)引入原因命名空间的定义命名空间成员的使用引入原因在一个给定作用域中定义的每个名字在该作用域中必须唯一的,对庞大、复杂的应用程序来说,这个要求难以满足由独立开发的库构成的复杂程序更有可能遇到名字冲突——比如我们定义的名字可能与库中的名字产生冲突通常可以通过把变量名设得很长来避免命名空间污染,但编写和阅读使用长名字的程序非常麻烦。命名空间为防止名字冲突提供了更加可控的机制,命名空间能够划分全局命名空间,这样使用独立开发的库更加容易。一个命名空间是一个作用域。命名空间的定义命名空间定义以关键字namespace开始,后接命名空间的名字。

namespacetest_namespace{ inta;

voidadd(); }这段代码定义了名为test_namespace的命名空间,它有两个成员,一个int类型变量,一个函数。命名空间名字后面接着由花括号括住的一块声明和定义。成员函数可以放在命名空间外定义,与类相同。命名空间作用域不能以分号结束此处跟类不一样,不需要加分号。命名空间的定义命名空间的名字在定义该命名空间的作用域中必须是唯一的命名空间可以在全局作用域或其他作用域内部定义,但不能再函数或类内部定义命名空间可以是不连续的:命名空间可以在几个部分中定义(比如在不同文件),命名空间有它的分离定义部分的总和构成。定义在全局作用域的名字是定义在全局命名空间中的。全局命名空间是隐式声明的,存在于每个程序中。命名空间可以是未命名的,未命名的命名空间在定义时没有给定名字。命名空间可以嵌套定义,如右所示namespacenamespace1{namespacenamespace2{

……

}

……}命名空间成员的使用域操作符(::):域操作符的含义是右操作数的名

温馨提示

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

评论

0/150

提交评论