《C++教程英文版.ppt》由会员分享,可在线阅读,更多相关《C++教程英文版.ppt(85页珍藏版)》请在三一办公上搜索。
1、1,10,Classes:ADeeper Look,Part 2,2,10.1 Introduction,const objects and const member functionsPrevent modifications of objects Enforce the principle of least privilegeCompositionClasses having objects of other classes as membersFriendshipEnables class designer to specify that certain non-member funct
2、ions can access the classs non-public members,3,10.1 Introduction(Cont.),this pointerDynamic memory managementnew and delete operatorsstatic class membersProxy classes Hide implementation details of a class from clientsPointer-base stringsUsed in C legacy code from the last two decades,4,10.2 const(
3、Constant)Objects and const Member Functions,Principle of least privilege One of the most fundamental principles of good software engineeringApplies to objects,tooconst objectsKeyword constSpecifies that an object is not modifiable Attempts to modify the object will result in compilation errors,5,10.
4、2 const(Constant)Objects and const Member Functions(Cont.),const member functionsOnly const member function can be called for const objectsMember functions declared const are not allowed to modify the object A function is specified as const both in its prototype and in its definitionconst declaratio
5、ns are not allowed for constructors and destructors,6,Software Engineering Observation 10.2,A const member function can be overloaded with a non-const version.The compiler chooses which overloaded member function to use based on the object on which the function is invoked.If the object is const,the
6、compiler uses the const version.If the object is not const,the compiler uses the non-const version.,7,Common Programming Error 10.4,Attempting to declare a constructor or destructor const is a compilation error.,8,Outline,Time.h(1 of 2),const keyword to indicate that member function cannot modify th
7、e object,9,Outline,Time.h(2 of 2),10,Outline,Time.cpp(1 of 3),11,Outline,Time.cpp(2 of 3),12,Outline,Time.cpp(3 of 3),13,Outline,fig10_03.cpp(1 of 2),Cannot invoke non-const member functions on a const object,14,Outline,fig10_03.cpp(2 of 2),15,10.2 const(Constant)Objects and const Member Functions(C
8、ont.),Member initializer Required for initializingconst 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 parameter list with a colon(:
9、)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,16,Outline,Increment.h(1 of 1),const data member that must be initialized usi
10、ng a member initializer,17,Outline,Increment.cpp(1 of 1),Colon(:)marks the start of a member initializer list,Member initializer for non-const member count,Required member initializer for const member increment,18,Outline,fig10_06.cpp(1 of 1),19,Outline,Increment.h(1 of 1),Member function declared c
11、onst to prevent errors in situations where an Increment object is treated as a const object,20,Outline,Increment.cpp(1 of 1),It is an error to modify a const data member;data member increment must be initialized with a member initializer,21,Outline,fig10_09.cpp(1 of 2),22,Outline,fig10_09.cpp(2 of 2
12、),23,10.3 Composition:Objects as Members of Classes,CompositionSometimes referred to as a has-a relationshipA class can have objects of other classes as membersExampleAlarmClock object with a Time object as a member,24,10.3 Composition:Objects as Members of Classes(Cont.),Initializing member objects
13、Member initializers pass arguments from the objects constructor to member-object constructorsMember 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(hos
14、t object)is constructedIf a member initializer is not providedThe member objects default constructor will be called implicitly,25,Software Engineering Observation 10.6,Member objects are constructed in the order in which they are declared in the class definition(not in the order they are listed in t
15、he constructors member initializer list)and before their enclosing class objects(sometimes called host objects)are constructed.,26,Outline,Date.h(1 of 1),27,Outline,Date.cpp(1 of 3),28,Outline,Date.cpp(2 of 3),29,Outline,Date.cpp(3 of 3),30,Outline,Employee.h(1 of 1),Parameters to be passed via memb
16、er initializers to the constructor for class Date,const objects of class Date as members,31,Outline,Employee.cpp(1 of 2),Member initializers that pass arguments to Dates implicit default copy constructor,32,Outline,Employee.cpp(2 of 2),33,Outline,fig10_14.cpp(1 of 2),Passing objects to a host object
17、 constructor,34,Outline,fig10_14.cpp(2 of 2),35,10.4 friend Functions and friend Classes,friend function of a class Defined outside that classs scopeNot a member function of that classYet has the right to access the non-public(and public)members of that classStandalone functions or entire classes ma
18、y be declared to be friends of a class Can enhance performanceOften appropriate when a member function cannot be used for certain operations,36,10.4 friend Functions and friend Classes(Cont.),To declare a function as a friend of a class:Provide the function prototype in the class definition preceded
19、 by keyword friendTo declare a class as a friend of a class:Place a declaration of the form friend class ClassTwo;in the definition of class ClassOneAll member functions of class ClassTwo are friends of class ClassOne,37,10.4 friend Functions and friend Classes(Cont.),Friendship is granted,not taken
20、For class B to be a friend of class A,class A must explicitly declare that class B is its friendFriendship relation is neither symmetric nor transitiveIf class A is a friend of class B,and class B is a friend of class C,you cannot infer that class B is a friend of class A,that class C is a friend of
21、 class B,or that class A is a friend of class C It is possible to specify overloaded functions as friends of a classEach overloaded function intended to be a friend must be explicitly declared as a friend of the class,38,Software Engineering Observation 10.10,Some people in the OOP community feel th
22、at“friendship”corrupts information hiding and weakens the value of the object-oriented design approach.In this text,we identify several examples of the responsible use of friendship.,39,Outline,fig10_15.cpp(1 of 2),friend function declaration(can appear anywhere in the class),40,Outline,fig10_15.cpp
23、(2 of 2),friend function can modify Counts private data,Calling a friend function;note that we pass the Count object to the function,41,Outline,fig10_16.cpp(1 of 3),42,Outline,fig10_16.cpp(2 of 3),Non-friend function cannot access the classs private data,43,Outline,fig10_16.cpp(3 of 3),Classes Part
24、II,friend Class Example,/ClassTwo Interface class ClassTwo friend class ClassOne;public:/constructor ClassTwo():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;,
25、/ClassOne Interface#include“classtwo.h”class ClassOne public:void setX(int val)c.x=val;void setY(int val)c.y=val;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;,Classes Part II,CIS 554/45,friend Class Exampletest driver and output,#incl
26、ude classone.hvoid main()ClassOne c1;c1.print();c1.setX(5);c1.setY(10);c1.setZ(15);c1.print();,46,10.5 Using the this Pointer,Member functions know which objects data members to manipulate Every object has access to its own address through a pointer called this(a C+keyword)An objects this pointer is
27、 not part of the object itselfThe this pointer is passed(by the compiler)as an implicit argument to each of the objects non-static member functionsObjects use the this pointer implicitly or explicitlyImplicitly when accessing members directlyExplicitly when using keyword thisType of the this pointer
28、 depends on the type of the object and whether the executing member function is declared const,47,Outline,fig10_17.cpp(1 of 2),48,Outline,fig10_17.cpp(2 of 2),Implicitly using the this pointer to access member x,Explicitly using the this pointer to access member x,Using the dereferenced this pointer
29、 and the dot operator,49,10.5 Using the this Pointer(Cont.),Cascaded member-function callsMultiple functions are invoked in the same statementEnabled by member functions returning the dereferenced this pointerExamplet.setMinute(30).setSecond(22);Calls t.setMinute(30);Then calls t.setSecond(22);,50,O
30、utline,Time.h(1 of 2),set functions return Time&to enable cascading,51,Outline,Time.h(2 of 2),52,Outline,Time.cpp(1 of 3),Returning dereferenced this pointer enables cascading,53,Outline,Time.cpp(2 of 3),54,Outline,Time.cpp(3 of 3),55,Outline,fig10_20.cpp(1 of 2),Cascaded function calls using the re
31、ference returned by one function call to invoke the next,Note that these calls must appear in the order shown,because printStandard does not return a reference to t,56,Outline,fig10_20.cpp(2 of 2),57,10.6 Dynamic Memory Management with Operators new and delete,Dynamic memory managementEnables progra
32、mmers to allocate and deallocate memory for any built-in or user-defined typePerformed by operators new and deleteFor example,dynamically allocating memory for an array instead of using a fixed-size array,58,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Operator newAllocates(i.
33、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 new Can be used to dynamically allocate any fundamental type(such as int or double)or any class typeFree storeSometimes called the
34、 heapRegion of memory assigned to each program for storing objects created at execution time,59,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Operator deleteDestroys a dynamically allocated object Calls the destructor for the objectDeallocates(i.e.,releases)memory from the free
35、 storeThe memory can then be reused by the system to allocate other objects,60,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Initializing an object allocated by newInitializer for a newly created fundamental-type variableExampledouble*ptr=new double(3.14159);Specify a comma-sep
36、arated list of arguments to the constructor of an objectExampleTime*timePtr=new Time(12,45,0);,61,Common Programming Error 10.8,Not 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“memory leak.”,62,10.
37、6 Dynamic Memory Management with Operators new and delete(Cont.),new operator can be used to allocate arrays dynamicallyDynamically allocate a 10-element integer array:int*gradesArray=new int 10;also:int arraySize=5;/non-constint*myArray=new intarraySize;delete myArraySize of a dynamically allocated
38、 arraySpecified using any integral expression that can be evaluated at execution time,63,10.6 Dynamic Memory Management with Operators new and delete(Cont.),Delete a dynamically allocated array:delete gradesArray;This deallocates the array to which gradesArray points If the pointer points to an arra
39、y of objectsFirst calls the destructor for every object in the arrayThen deallocates the memory If the statement did not include the square brackets()and gradesArray pointed to an array of objectsOnly the first object in the array would have a destructor call,64,Common Programming Error 10.9,Using d
40、elete instead of delete for arrays of objects can lead to runtime logic errors.To ensure that every object in the array receives a destructor call,always delete memory allocated as an array with operator delete.Similarly,always delete memory allocated as an individual element with operator delete;ot
41、herwise,the result of the operation is undefined.,65,10.7 static Class Members,static data memberOnly one copy of a variable shared by all objects of a class“Class-wide”information A property of the class shared by all instances,not a property of a specific object of the classDeclaration begins with
42、 keyword static,66,10.7 static Class Members(Cont.),static data member(Cont.)ExampleVideo game with Martians and other space creaturesEach Martian needs to know the martianCountmartianCount should be static class-wide dataEvery Martian can access martianCount as if it were a data member of that Mart
43、ianOnly one copy of martianCount existsMay seem like global variables but they have class scopeCan be declared public,private or protected,67,10.7 static Class Members(Cont.),static data member(Cont.)Fundamental-type static data members Initialized by default to 0If you want a different initial valu
44、e,a static data member can be initialized once(and only once)A const static data member of int or enum typeCan be initialized in its declaration in the class definition All other static data membersMust be defined at file scope(i.e.,outside the body of the class definition)Can be initialized only in
45、 those definitionsstatic data members of class types(i.e.,static member objects)that have default constructorsNeed not be initialized because their default constructors will be called,68,10.7 static Class Members(Cont.),static data member(Cont.)Exists even when no objects of the class existTo access
46、 a public static class member when no objects of the class existPrefix the class name and the binary scope resolution operator(:)to the name of the data member ExampleMartian:martianCountAlso accessible through any object of that classUse the objects name,the dot operator and the name of the memberE
47、xamplemyMartian.martianCount,69,10.7 static Class Members(Cont.),static member functionIs a service of the class,not of a specific object of the classstatic applied to an item at file scopeThat item becomes known only in that fileThe static members of the class need to be available from any client c
48、ode that accesses the fileSo we cannot declare them static in the.cpp filewe declare them static only in the.h file.,70,Software Engineering Observation 10.11,A classs static data members and static member functions exist and can be used even if no objects of that class have been instantiated.,71,Ou
49、tline,fig10_21.cpp(1 of 1),Function prototype for static member function,static data member keeps track of number of Employee objects that currently exist,72,Outline,Employee.cpp(1 of 3),static data member is defined and initialized at file scope in the.cpp file,static member function can access onl
50、y static data,because the function might be called when no objects exist,73,Outline,Employee.cpp(2 of 3),Dynamically allocating char arrays,Non-static member function(i.e.,constructor)can modify the classs static data members,Deallocating memory reserved for arrays,74,Outline,Employee.cpp(3 of 3),75