《C++教程英文版.ppt》由会员分享,可在线阅读,更多相关《C++教程英文版.ppt(85页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、 2008 Pearson Education,Inc.All rights reserved.110Classes:ADeeperLook,Part2 2008 Pearson Education,Inc.All rights reserved.210.1Introductionconstconst objects and constconst member functionsPrevent modifications of objects Enforce the principle of least privilegeCompositionClasses having objects of
2、 other classes as membersFriendshipEnables class designer to specify that certain non-member functions can access the classs non-publicpublic members 2008 Pearson Education,Inc.All rights reserved.310.1Introduction(Cont.)thisthis pointerDynamic memory managementnewnew and deletedelete operatorsstati
3、cstatic class membersProxy classes Hide implementation details of a class from clientsPointer-base stringsUsed in C legacy code from the last two decades 2008 Pearson Education,Inc.All rights reserved.410.2constconst(Constant)ObjectsandconstconstMemberFunctionsPrinciple of least privilege One of the
4、 most fundamental principles of good software engineeringApplies to objects,tooconstconst objectsKeyword constconstSpecifies that an object is not modifiable Attempts to modify the object will result in compilation errors 2008 Pearson Education,Inc.All rights reserved.510.2constconst(Constant)Object
5、sandconstconstMemberFunctions(Cont.)constconst member functionsOnly constconst member function can be called for constconst objectsMember functions declared constconst are not allowed to modify the object A function is specified as constconst both in its prototype and in its definitionconstconst dec
6、larations are not allowed for constructors and destructors 2008 Pearson Education,Inc.All rights reserved.6SoftwareEngineeringObservation10.2A constconst member function can be overloaded with a non-constconst version.The compiler chooses which overloaded member function to use based on the object o
7、n which the function is invoked.If the object is constconst,the compiler uses the constconst version.If the object is not constconst,the compiler uses the non-constconst version.2008 Pearson Education,Inc.All rights reserved.7CommonProgrammingError10.4Attempting to declare a constructor or destructo
8、r constconst is a compilation error.2008 Pearson Education,Inc.All rights reserved.8OutlineTime.hTime.h (1 of 2)const keyword to indicate that member function cannot modify the object 2008 Pearson Education,Inc.All rights reserved.9OutlineTime.hTime.h (2 of 2)2008 Pearson Education,Inc.All rights re
9、served.10OutlineTime.cppTime.cpp (1 of 3)2008 Pearson Education,Inc.All rights reserved.11OutlineTime.cppTime.cpp (2 of 3)const keyword in function definition,as well as in function prototype 2008 Pearson Education,Inc.All rights reserved.12OutlineTime.cppTime.cpp (3 of 3)2008 Pearson Education,Inc.
10、All rights reserved.13Outlinefig10_03.cppfig10_03.cpp (1 of 2)Cannot invoke non-const member functions on a const object 2008 Pearson Education,Inc.All rights reserved.14Outlinefig10_03.cppfig10_03.cpp (2 of 2)2008 Pearson Education,Inc.All rights reserved.1510.2constconst(Constant)Objectsandconstco
11、nstMemberFunctions(Cont.)Member initializer Required for initializingconstconst data membersData members that are referencesCan be used for any data memberMember initializer listAppears between a constructors parameter list and the left brace that begins the constructors bodySeparated from the param
12、eter list with a colon(:)Each member initializer consists of the data member name followed by parentheses containing the members initial valueMultiple member initializers are separated by commasExecutes before the body of the constructor executes 2008 Pearson Education,Inc.All rights reserved.16Outl
13、ineIncrement.hIncrement.h (1 of 1)const data member that must be initialized using a member initializer 2008 Pearson Education,Inc.All rights reserved.17OutlineIncrement.cppIncrement.cpp(1 of 1)Colon(:)marks the start of a member initializer listMember initializer for non-const member countRequired
14、member initializer for const member increment 2008 Pearson Education,Inc.All rights reserved.18Outlinefig10_06.cppfig10_06.cpp (1 of 1)2008 Pearson Education,Inc.All rights reserved.19OutlineIncrement.hIncrement.h (1 of 1)Member function declared const to prevent errors in situations where an Increm
15、ent object is treated as a const object 2008 Pearson Education,Inc.All rights reserved.20OutlineIncrement.cppIncrement.cpp (1 of 1)It is an error to modify a const data member;data member increment must be initialized with a member initializer 2008 Pearson Education,Inc.All rights reserved.21Outline
16、fig10_09.cppfig10_09.cpp (1 of 2)2008 Pearson Education,Inc.All rights reserved.22Outlinefig10_09.cppfig10_09.cpp (2 of 2)2008 Pearson Education,Inc.All rights reserved.2310.3Composition:ObjectsasMembersofClassesCompositionSometimes referred to as a has-a relationshipA class can have objects of othe
17、r classes as membersExampleAlarmClockAlarmClock object with a TimeTime object as a member 2008 Pearson Education,Inc.All rights reserved.2410.3Composition:ObjectsasMembersofClasses(Cont.)Initializing member objectsMember initializers pass arguments from the objects constructor to member-object const
18、ructorsMember objects are constructed in the order in which they are declared in the class definitionNot in the order they are listed in the constructors member initializer listBefore the enclosing class object(host object)is constructedIf a member initializer is not providedThe member objects defau
19、lt constructor will be called implicitly 2008 Pearson Education,Inc.All rights reserved.25SoftwareEngineeringObservation10.6Member objects are constructed in the order in which they are declared in the class definition(not in the order they are listed in the constructors member initializer list)and
20、before their enclosing class objects(sometimes called host objects)are constructed.2008 Pearson Education,Inc.All rights reserved.26OutlineDate.hDate.h (1 of 1)2008 Pearson Education,Inc.All rights reserved.27OutlineDate.cppDate.cpp (1 of 3)2008 Pearson Education,Inc.All rights reserved.28OutlineDat
21、e.cppDate.cpp (2 of 3)2008 Pearson Education,Inc.All rights reserved.29OutlineDate.cppDate.cpp (3 of 3)2008 Pearson Education,Inc.All rights reserved.30OutlineEmployee.hEmployee.h (1 of 1)Parameters to be passed via member initializers to the constructor for class Dateconst objects of class Date as
22、members 2008 Pearson Education,Inc.All rights reserved.31OutlineEmployee.cppEmployee.cpp(1 of 2)Member initializers that pass arguments to Dates implicit default copy constructor 2008 Pearson Education,Inc.All rights reserved.32OutlineEmployee.cppEmployee.cpp(2 of 2)2008 Pearson Education,Inc.All ri
23、ghts reserved.33Outlinefig10_14.cppfig10_14.cpp(1 of 2)Passing objects to a host object constructor 2008 Pearson Education,Inc.All rights reserved.34Outlinefig10_14.cppfig10_14.cpp(2 of 2)2008 Pearson Education,Inc.All rights reserved.3510.4friendfriendFunctionsandfriendfriendClassesfriendfriend fun
24、ction of a class Defined outside that classs scopeNot a member function of that classYet has the right to access the non-publicpublic(and publicpublic)members of that classStandalone functions or entire classes may be declared to be friends of a class Can enhance performanceOften appropriate when a
25、member function cannot be used for certain operations 2008 Pearson Education,Inc.All rights reserved.3610.4friendfriendFunctionsandfriendfriendClasses(Cont.)To declare a function as a friendfriend of a class:Provide the function prototype in the class definition preceded by keyword friendfriendTo de
26、clare a class as a friend of a class:Place a declaration of the form friend class ClassTwo;friend class ClassTwo;in the definition of class ClassOneClassOneAll member functions of class ClassTwoClassTwo are friendfriends of class ClassOneClassOne 2008 Pearson Education,Inc.All rights reserved.3710.4
27、friendfriendFunctionsandfriendfriendClasses(Cont.)Friendship is granted,not takenFor class B B to be a friend of class A A,class A A must explicitly declare that class B B is its friendFriendship relation is neither symmetric nor transitiveIf class A A is a friend of class B B,and class B B is a fri
28、end of class C C,you cannot infer that class B B is a friend of class A A,that class C C is a friend of class B B,or that class A A is a friend of class C C It is possible to specify overloaded functions as friendfriends of a classEach overloaded function intended to be a friendfriend must be explic
29、itly declared as a friendfriend of the class 2008 Pearson Education,Inc.All rights reserved.38SoftwareEngineeringObservation10.10Some people in the OOP community feel that“friendship”corrupts information hiding and weakens the value of the object-oriented design approach.In this text,we identify sev
30、eral examples of the responsible use of friendship.2008 Pearson Education,Inc.All rights reserved.39Outlinefig10_15.cppfig10_15.cpp(1 of 2)friend function declaration(can appear anywhere in the class)2008 Pearson Education,Inc.All rights reserved.40Outlinefig10_15.cppfig10_15.cpp(2 of 2)friend funct
31、ion can modify Counts private dataCalling a friend function;note that we pass the Count object to the function 2008 Pearson Education,Inc.All rights reserved.41Outlinefig10_16.cppfig10_16.cpp(1 of 3)2008 Pearson Education,Inc.All rights reserved.42Outlinefig10_16.cppfig10_16.cpp(2 of 3)Non-friend fu
32、nction cannot access the classs private data 2008 Pearson Education,Inc.All rights reserved.43Outlinefig10_16.cppfig10_16.cpp(3 of 3)2008 Pearson Education,Inc.All rights reserved.Classes Part IIfriend Class Example/ClassTwo Interface class ClassTwo friend class ClassOne;public:/constructor ClassTwo
33、():x(0),y(0),z(0)/no body void print()const cout x=x endl;cout y=y endl;cout z=z endl;private:int x,y,z;/data members void setX(int val)x=val;void setY(int val)y=val;void setZ(int val)z=val;/ClassOne Interface#include“classtwo.h”class ClassOne public:void setX(int val)c.x=val;void setY(int val)c.y=v
34、al;void setZ(int val)c.z=val;void print()const cout x=c.x endl;cout y=c.y endl;cout z=c.z endl;private:ClassTwo c;2008 Pearson Education,Inc.All rights reserved.Classes Part IICIS 554/45friend Class Exampletest driver and output#include classone.hvoid main()ClassOne c1;c1.print();c1.setX(5);c1.setY(
35、10);c1.setZ(15);c1.print();2008 Pearson Education,Inc.All rights reserved.4610.5UsingthethisthisPointerMember functions know which objects data members to manipulate Every object has access to its own address through a pointer called thisthis(a C+keyword)An objects thisthis pointer is not part of th
36、e object itselfThe thisthis pointer is passed(by the compiler)as an implicit argument to each of the objects non-staticstatic member functionsObjects use the thisthis pointer implicitly or explicitlyImplicitly when accessing members directlyExplicitly when using keyword thisthisType of the thisthis
37、pointer depends on the type of the object and whether the executing member function is declared constconst 2008 Pearson Education,Inc.All rights reserved.47Outlinefig10_17.cppfig10_17.cpp(1 of 2)2008 Pearson Education,Inc.All rights reserved.48Outlinefig10_17.cppfig10_17.cpp(2 of 2)Implicitly using
38、the this pointer to access member xExplicitly using the this pointer to access member xUsing the dereferenced this pointer and the dot operator 2008 Pearson Education,Inc.All rights reserved.4910.5UsingthethisthisPointer(Cont.)Cascaded member-function callsMultiple functions are invoked in the same
39、statementEnabled by member functions returning the dereferenced thisthis pointerExamplet.setMinute(30).setSecond(22);t.setMinute(30).setSecond(22);Calls t.setMinute(30);t.setMinute(30);Then calls t.setSecond(22);t.setSecond(22);2008 Pearson Education,Inc.All rights reserved.50OutlineTime.hTime.h(1 o
40、f 2)set functions return Time&to enable cascading 2008 Pearson Education,Inc.All rights reserved.51OutlineTime.hTime.h(2 of 2)2008 Pearson Education,Inc.All rights reserved.52OutlineTime.cppTime.cpp(1 of 3)Returning dereferenced this pointer enables cascading 2008 Pearson Education,Inc.All rights re
41、served.53OutlineTime.cppTime.cpp(2 of 3)2008 Pearson Education,Inc.All rights reserved.54OutlineTime.cppTime.cpp(3 of 3)2008 Pearson Education,Inc.All rights reserved.55Outlinefig10_20.cppfig10_20.cpp(1 of 2)Cascaded function calls using the reference returned by one function call to invoke the next
42、Note that these calls must appear in the order shown,because printStandard does not return a reference to t 2008 Pearson Education,Inc.All rights reserved.56Outlinefig10_20.cppfig10_20.cpp(2 of 2)2008 Pearson Education,Inc.All rights reserved.5710.6DynamicMemoryManagementwithOperatorsnewnewanddelete
43、deleteDynamic memory managementEnables programmers to allocate and deallocate memory for any built-in or user-defined typePerformed by operators newnew and deletedeleteFor example,dynamically allocating memory for an array instead of using a fixed-size array 2008 Pearson Education,Inc.All rights res
44、erved.5810.6DynamicMemoryManagementwithOperatorsnewnewanddeletedelete(Cont.)Operator newnewAllocates(i.e.,reserves)storage of the proper size for an object at execution timeCalls a constructor to initialize the objectReturns a pointer of the type specified to the right of newnew Can be used to dynam
45、ically allocate any fundamental type(such as intint or doubledouble)or any class typeFree storeSometimes called the heapRegion of memory assigned to each program for storing objects created at execution time 2008 Pearson Education,Inc.All rights reserved.5910.6DynamicMemoryManagementwithOperatorsnew
46、newanddeletedelete(Cont.)Operator deletedeleteDestroys a dynamically allocated object Calls the destructor for the objectDeallocates(i.e.,releases)memory from the free storeThe memory can then be reused by the system to allocate other objects 2008 Pearson Education,Inc.All rights reserved.6010.6Dyna
47、micMemoryManagementwithOperatorsnewnewanddeletedelete(Cont.)Initializing an object allocated by newnewInitializer for a newly created fundamental-type variableExampledouble*ptr=new double(3.14159);double*ptr=new double(3.14159);Specify a comma-separated list of arguments to the constructor of an obj
48、ectExampleTime*timePtrTime*timePtr=newnew Time(12,45,0);Time(12,45,0);2008 Pearson Education,Inc.All rights reserved.61CommonProgrammingError10.8Not releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely.This is sometimes called a“mem
49、ory leak.”2008 Pearson Education,Inc.All rights reserved.6210.6DynamicMemoryManagementwithOperatorsnewnewanddeletedelete(Cont.)newnew operator can be used to allocate arrays dynamicallyDynamically allocate a 10-element integer array:int*gradesArray=new int 10;int*gradesArray=new int 10;also:also:int
50、 arraySize=5;/non-constint arraySize=5;/non-constint*myArray=new intarraySize;int*myArray=new intarraySize;delete myArraydelete myArraySize of a dynamically allocated arraySpecified using any integral expression that can be evaluated at execution time 2008 Pearson Education,Inc.All rights reserved.6