1、Chapter 16: Classes and Data Abstraction,Outline 16.1 Introduction 16.2 Implementing a Time Abstract Data Type with a Class 16.3 Class Scope and Accessing Class Members 16.4 Separating Interface from Implementation 16.5 Controlling Access to Members 16.6 Access Functions and Utility Functions 16.7 I
2、nitializing Class Objects: Constructors 16.8 Using Default Arguments with Constructors 16.9 Using Destructors 16.10 When Constructors and Destructors Are Called 16.11 Using Data Members and Member Functions 16.12 A Subtle Trap: Returning a Reference to a private Data Member 16.13 Assignment by Defau
3、lt Memberwise Copy 16.14 Software Reusability,Objectives,In this chapter, you will learn: To understand the software engineering concepts of encapsulation and data hiding. To understand the notions of data abstraction and abstract data types (ADTs). To be able to create C+ ADTs, namely classes. To u
4、nderstand how to create, use, and destroy class objects. To be able to control access to object data members and member functions. To begin to appreciate the value of object orientation.,16.1 Introduction,Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into
5、packages called classes Data and functions closely relatedInformation hiding Implementation details are hidden within the classes themselvesUnit of C+ programming: the class A class is like a blueprint reusable Objects are instantiated (created) from the class For example, a house is an instance of
6、a “blueprint class” C programmers concentrate on functions,16.2 Implementing a Time Abstract Data Type with a Class,Classes Model objects that have attributes (data members) and behaviors (member functions) Defined using keyword class,Public: and Private: are member-access specifiers.,setTime, print
7、Military, and printStandard are member functions. Time is the constructor.,hour, minute, and second are data members.,16.2 Implementing a Time Abstract Data Type with a Class (II),Format Body delineated with braces ( and ) Class definition terminates with a semicolonMember functions and data Public
8、- accessible wherever the program has access to an object of class TimePrivate - accessible only to member functions of the class Protected - discussed later in the course,16.2 Implementing a Time Abstract Data Type with a Class (III),Constructor Special member function that initializes data members
9、 of a class object Constructors cannot return values Same name as the class Definitions Once class defined, can be used as a data type,16.2 Implementing a Time Abstract Data Type with a Class (IV),Binary scope resolution operator (:) Specifies which class owns the member function Different classes c
10、an have the same name for member functionsFormat for definition class member functionsReturnType ClassName:MemberFunctionName( ),16.2 Implementing a Time Abstract Data Type with a Class (V),If member function is defined inside the class Scope resolution operator and class name are not needed Definin
11、g a function outside a class does not change it being public or privateClasses encourage software reuse Inheritance allows new classes to be derived from old onesIn following program Time constructor initializes the data members to 0 Ensures that the object is in a consistent state when it is create
12、d,fig16_02.cpp (Part 1 of 3),fig16_02.cpp (Part 2 of 3),fig16_02.cpp (Part 3 of 3),Program Output,The initial military time is 00:00 The initial standard time is 12:00:00 AMMilitary time after setTime is 13:27 Standard time after setTime is 1:27:06 PMAfter attempting invalid settings: Military time:
13、 00:00 Standard time: 12:00:00 AM,16.3 Class Scope and Accessing Class Members,Class scope Data members and member functions File scope Nonmember functions Function scope Variables defined in member functions, destroyed after function completes Inside a scope Members accessible by all member functio
14、ns Referenced by name,16.3 Class Scope and Accessing Class Members (II),Outside a scope Use handles An object name, a reference to an object or a pointer to an object Accessing class members Same as structs Dot (.) for objects and arrow (-) for pointers Example: t.hour is the hour element of t TimeP
15、tr-hour is the hour element,fig16_03.cpp (Part 1 of 2),fig16_03.cpp (Part 2 of 2) Program Output,Assign 7 to x and print using the objects name: 7 Assign 8 to x and print using a reference: 8 Assign 10 to x and print using a pointer: 10,16.4 Separating Interface from Implementation,Separating interf
16、ace from implementation Easier to modify programs C+ programs can be split intoHeader files contains class definitions and function prototypesSource-code files contains member function definitionsProgram Outline: Using the same Time class as before, create a header file Create a source code file Loa
17、d the header file to get the class definitions Define the member functions of the class,time1.h,time1.cpp (Part 1 of 2),time1.cpp (Part 2 of 2),fig16_04.cpp (Part 1 of 2),fig16_04.cpp (Part 2 of 2) Program Output,The initial military time is 00:00 The initial standard time is 12:00:00 AMMilitary tim
18、e after setTime is 13:27 Standard time after setTime is 1:27:06 PMAfter attempting invalid settings: Military time: 00:00 Standard time: 12:00:00 AM,16.5 Controlling Access to Members,Purpose of public Give clients a view of the services the class provides (interface) Purpose of private Default sett
19、ing Hide details of how the class accomplishes its tasks (implementation) Private members only accessible through the public interface using public member functions,fig16_05.cpp,Program Output,Borland C+ command-line compiler error messages,Time1.cpp: Fig16_05.cpp: Error E2247 Fig16_05.cpp 15: Time:
20、hour is not accessible in function main() Error E2247 Fig16_05.cpp 18: Time:minute is not accessible in function main()* 2 errors in Compile *,Microsoft Visual C+ compiler error messages,Compiling. Fig16_05.cpp D:Fig16_05.cpp(15) : error C2248: hour : cannot access private member declared in class T
21、ime D:Fig16_05time1.h(18) : see declaration of hour D:Fig16_05.cpp(18) : error C2248: minute : cannot access private member declared in class Time D:time1.h(19) : see declaration of minute Error executing cl.exe.test.exe - 2 error(s), 0 warning(s),16.6 Access Functions and Utility Functions,Utility
22、functions private functions that support the operation of public functions Not intended to be used directly by clients Access functions public functions that read/display data or check conditions For a container, it could call the isEmpty function Next Program to take in monthly sales and output the
23、 total Implementation not shown, only access functions,salesp.h,salesp.cpp (Part 1 of 3),salesp.cpp (Part 2 of 3),salesp.cpp (Part 3 of 3),fig16_06.cpp Program Output,Enter sales amount for month 1: 5314.76 Enter sales amount for month 2: 4292.38 Enter sales amount for month 3: 4589.83 Enter sales a
24、mount for month 4: 5534.03 Enter sales amount for month 5: 4376.34 Enter sales amount for month 6: 5698.45 Enter sales amount for month 7: 4439.22 Enter sales amount for month 8: 5893.57 Enter sales amount for month 9: 4909.67 Enter sales amount for month 10: 5123.45 Enter sales amount for month 11:
25、 4024.97 Enter sales amount for month 12: 5923.92The total annual sales are: $60120.59,16.7 Initializing Class Objects: Constructors,Constructor function Can initialize class members Same name as the class, no return type Member variables can be initialized by the constructor or set afterwardsDefini
26、ng objects Initializers can be provided Initializers passed as arguments to the class constructor,16.7 Initializing Class Objects: Constructors (II),FormatType ObjectName( value1, value2, ); Constructor assigns value1, value2, etc. to its member variables If not enough values specified, rightmost pa
27、rameters set to their default (specified by programmer)myClass myObject( 3, 4.0 );,16.8 Using Default Arguments with Constructors,Default constructor One per class Can be invoked without arguments Has default arguments Default arguments Set in default constructor function prototype (in class definit
28、ion) Do not set defaults in the function definition, outside of a class Example: SampleClass( int = 0, float = 0); Constructor has same name as class,time2.h,time2.cpp (Part 1 of 2),time2.cpp (Part 2 of 2),fig16_07.cpp (Part 1 of 2),fig16_07.cpp (Part 2 of 2),Program Output,Constructed with: all arg
29、uments defaulted:00:0012:00:00 AM hour specified; minute and second defaulted:02:002:00:00 AM hour and minute specified; second defaulted:21:349:34:00 PM hour, minute, and second specified:12:2512:25:42 PM all invalid values specified:00:0012:00:00 AM,16.9 Using Destructors,Destructor Member functio
30、n of class Performs termination housekeeping before the system reclaims the objects memory Complement of the constructor Name is tilde () followed by the class name Time Recall that the constructors name is the class name Receives no parameters, returns no value One destructor per class - no overloa
31、ding allowed,16.10 When Constructors and Destructors Are Called,Constructors and destructors called automatically Order depends on scope of objectsGlobal scope objects Constructors called before any other function (including main) Destructors called when main terminates (or exit function called) Des
32、tructors not called if program terminates with abort,16.10 When Constructors and Destructors Are Called (II),Automatic local objects Constructors called when objects defined Destructors called when objects leave scope (when the block in which they are defined is exited) Destructors not called if pro
33、gram ends with exit or abort static local objects Constructors called when execution reaches the point where the objects are defined Destructors called when main terminates or the exit function is called Destructors not called if the program ends with abort,create.h,create.cpp,fig16_08.cpp (Part 1 o
34、f 2),fig16_08.cpp (Part 2 of 2),Program Output,Object 1 constructor (global created before main) Object 2 constructor (local automatic in main) Object 3 constructor (local static in main) Object 5 constructor (local automatic in create) Object 6 constructor (local static in create) Object 7 construc
35、tor (local automatic in create) Object 7 destructor Object 5 destructor Object 4 constructor (local automatic in main) Object 4 destructor Object 2 destructor Object 6 destructor Object 3 destructor Object 1 destructor,16.11 Using Data Members and Member Functions,Classes provide public member funct
36、ions Set (i.e., write) or get (i.e., read) values of private data members Adjustment of bank balance (a private data member of class BankAccount) by member function computeInterest Naming Member function that sets interestRate typically named setInterestRate Member function that gets interestRate wo
37、uld typically be called getInterestRate,16.11 Using Data Members and Member Functions (II),Do set and get capabilities effectively make data members public? No! Programmer decides what the function can set and what information the function can getpublic set functions should Check attempts to modify
38、data members Ensure that the new value is appropriate for that data item Example: an attempt to set the day of the month to 37 would be rejected Programmer must include these features,time3.h (Part 1 of 2),time3.h (Part 2 of 2),time3.cpp (Part 1 of 3),time3.cpp (Part 2 of 3),time3.cpp (Part 3 of 3),
39、fig16_09.cpp (Part 1 of 3),fig16_09.cpp (Part 2 of 3),fig16_09.cpp (Part 3 of 3) Program Output,Result of setting all valid values:Hour: 17 Minute: 34 Second: 25Result of attempting to set invalid hour and second:Hour: 0 Minute: 43 Second: 0 Incrementing minute 3 times: Start time: 11:58:00 AM minut
40、e + 1: 11:59:00 AM minute + 1: 12:00:00 PM minute + 1: 12:01:00 PM,16.12 A Subtle Trap: Returning a Reference to a Private Data Member,Reference to an object Alias for the name of the object May be used on the left side of an assignment statement Reference can receive a value, which changes the orig
41、inal object as wellOne way to use this capability (unfortunately!) Have a public member function of a class return a non-const reference to a private data member This reference can be modified, which changes the original data,time4.h,time4.cpp (Part 1 of 2),time4.cpp (Part 2 of 2),fig16_10.cpp (Part
42、 1 of 2),fig16_10.cpp (Part 2 of 2) Program Output,Hour before modification: 20 Hour after modification: 30* POOR PROGRAMMING PRACTICE! badSetHour as an lvalue, Hour: 74 *,16.13 Assignment by Default Memberwise Copy,Assignment operator (=) Sets variables equal, i.e., x = y; Can be used to assign an
43、object to another object of the same type Memberwise copy member by member copymyObject1 = myObject2;Objects may be Passed as function arguments Returned from functions (call-by-value default) Use pointers for call by reference,fig16_11.cpp (Part 1 of 2),fig16_11.cpp (Part 2 of 2) Program Output,dat
44、e1 = 7-4-1993 date2 = 1-1-1990After default memberwise copy, date2 = 7-4-1993,16.14 Software Reusability,Object-oriented programmers Concentrate on implementing useful classesTremendous opportunity to capture and catalog classes Accessed by large segments of the programming community Class libraries exist for this purposeSoftware Constructed from existing, well-defined, carefully tested, portable, widely available components Speeds development of powerful, high-quality software,
copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1