1 / 82

Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington

Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington. Chapter 11 Topics. Meaning of a Structured Data Type Declaring and Using a struct Data Type C++ union Data Type Meaning of an Abstract Data Type Declaring and Using a class Data Type

joshua-cruz
Télécharger la présentation

Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington

  2. Chapter 11 Topics • Meaning of a Structured Data Type • Declaring and Using a struct Data Type • C++ union Data Type • Meaning of an Abstract Data Type • Declaring and Using a class Data Type • Using Separate Specification and Implementation Files • Invoking class Member Functions in Client Code • C++ class Constructors

  3. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool

  4. Structs

  5. Structured Data Type A structured data type is a type in which each value is a collection of component items. • the entire collection has a single name • each component can be accessed individually

  6. C++ Structured Type • often we have related information of various types that we’d like to store together for convenient access under the sameidentifier, for example . . .

  7. thisAnimal 5000 .id 2037581 .name “giant panda” .genus “Ailuropoda” .species “melanoluka” .country “China” .age 18 .weight 234.6 .health Good

  8. anotherAnimal 6000 .id 5281003 .name “llama” .genus “Lama” .species “peruana” .country “Peru” .age 7 .weight 278.5 .health Excellent

  9. struct AnimalType enum HealthType { Poor, Fair, Good, Excellent } ; struct AnimalType// declares a struct data type {// does not allocate memory int id ; string name ; string genus ; string species ; struct members string country ; int age ; float weight ; } ; AnimalType thisAnimal ; // declare variables of AnimalType AnimalType anotherAnimal ;

  10. struct type Declaration SYNTAX struct TypeName // does not allocate memory { MemberList } ; MemberList SYNTAX DataType MemberName ; DataType MemberName ; . . .

  11. struct type Declaration The struct declaration names a type and names the members of the struct. It does not allocate memory for any variables of that type! You still need to declare your struct variables.

  12. More aboutstruct type declarations If struct type declaration precedes all functions visible throughout the rest of the file (global scope). If it is placed within a function, only that function can use it (local scope). Common to place struct type decl. in (.h) header file #include that file.

  13. More aboutstruct type declarations Members of different struct types MAY have the same identifiers (names). struct Student struct Instructor { {int id; int id; float gpa; float salary; } } Non-struct variable MAY have the same identifier as a structure member. Student s; float gpa;

  14. Accessingstruct Members Dot ( period ) is the member selection operator. After struct type declaration: struct members can be used in your program only when they are preceded by • dot • a struct variable name EXAMPLES AnimalType thisAnimal, anotherAnimal; thisAnimal.weight anotherAnimal.country

  15. Valid operations on a struct member depend only on its type struct AnimalType{long id ; string name ; string genus ; string species; string country int age ; float weight ; HealthType health ; } ; AnimalType thisAnimal; thisAnimal.age = 18; thisAnimal.id = 2037581; cin >> thisAnimal.weight; getline ( cin, thisAnimal.species ); thisAnimal.name = “giant panda”; thisAnimal.genus[ 0 ] = toupper (thisAnimal.genus[ 0 ] ) ; thisAnimal.age++;

  16. Aggregate Operations

  17. Aggregate Operation • is an operation on adata structure as a wholeas opposed to an operation on an individual component of the data structure

  18. Aggregatestruct Operations • NOT ALLOWED • I/O • arithmetic • comparisons of entire struct variables • Operations ALLOWED on entire struct variable: • assignment to another struct variable of same type • pass to a function as argument (by value or by reference) • return as value of a function see time1.cpp time2.cpp

  19. Examples of aggregate struct operations anotherAnimal = thisAnimal ; // assignment WriteOut(thisAnimal); // value parameter ChangeWeightAndAge(thisAnimal); // reference parameter thisAnimal = GetAnimalData( ); // return value of function NOW WE’LL WRITE THE 3 FUNCTIONS USED HERE . . .

  20. void WriteOut( /* in */ AnimalType thisAnimal) // Prints out values of all members of thisAnimal // Precondition: all members of thisAnimal are assigned // Postcondition: all members have been written out { cout << “ID # “ << thisAnimal.id << thisAnimal.name << endl ; cout << thisAnimal.genus << thisAnimal.species << endl ; cout << thisAnimal.country << endl ; cout << thisAnimal.age << “ years “ << endl ; cout << thisAnimal.weight << “ lbs. “ << endl ; cout << “General health : “ ; WriteWord ( thisAnimal.health ) ; }

  21. Passing a struct Type by Reference void ChangeAge ( /* inout */ AnimalType& thisAnimal ) // Adds 1 to age // Precondition: thisAnimal.age is assigned // Postcondition: thisAnimal.age == thisAnimal.age@entry + 1 { thisAnimal.age++ ; }

  22. AnimalType GetAnimalData ( void ) // Obtains all information about an animal from keyboard // Postcondition: // Function value == AnimalType members entered at kbd { AnimalType thisAnimal ; char response ; do { // have user enter all members until they are correct . . . } while (response != ‘Y’ ) ; return thisAnimal ; }

  23. Hierarchical Structures

  24. Hierarchical Structures A struct member can be of another struct type. This is called nested or hierarchical structures. Hierarchical structures are useful when there is detailed info in each record. FOR EXAMPLE . . .

  25. struct MachineRec Information about each machine in a shop contains: an idNumber, a written description, the purchase date, the cost, and a historical statistics (including failure rate, number of days down, and date of last service).

  26. struct DateType { int month ; // Assume 1 . . 12 int day ;// Assume 1 . . 31 int year ; // Assume 1900 . . 2050 }; struct StatisticsType { float failRate ; DateType lastServiced ; // DateType is a struct type int downDays ; } ; struct MachineRec { int idNumber ; string description ; StatisticsType history ; // StatisticsType is a struct type DateType purchaseDate ; float cost ; } ; MachineRec machine ;

  27. struct type variable machine 7000 5719 “BULLDOZ…” 3 21 1995 78000. .02 6 25 1999 4 .month .day .year .month .day .year .failrate .lastServiced .downdays .idNumber .description . history .purchaseDate .cost machine.history.lastServiced.year has value 1999

  28. Unions

  29. Unions in C++ DEFINITION A union is a struct that holds only one of its members at a time during program execution. EXAMPLE union WeightType { long wtInOunces ; int wtInPounds; only one at a time float wtInTons; } ;

  30. Using Unions union WeightType // declares a union type { long wtInOunces ; int wtInPounds; float wtInTons; } ; WeightType weight; // declares a union variable weight.wtInTons = 4.83 ; // Weight in tons is no longer needed. Reuse the memory space. weight.wtInPounds = 35; // see Unionex.cpp

  31. Abstraction

  32. Abstraction • Is the separation of the essential qualities of an object from the details of how it works or is composed Essential qualities <<<<>>>> details • Focuses on what, not how • Like a table of contents • Is necessary for managing large, complex software projects

  33. Control Abstraction • separates the logical properties of an action from its implementation logical properties <<<>>> implementation . . . Search (list, item, length, where, found); . . . • the function call depends on the function’s specification (description), not its implementation (algorithm)

  34. Data Abstraction • separates the logical properties of a data type from its implementation LOGICAL PROPERTIES IMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed? How can existing data types be used?

  35. Data Type set of values (domain) allowable operations on those values FOR EXAMPLE, data type short has operations +, -, *, /, %, >>, << domain -32768 . . . 32767

  36. Abstract Data Type

  37. Abstract Data Type (ADT) • a data type whose • properties (domain and operations) WHAT • are specified independently of any • particular implementation HOW FOR EXAMPLE . . .

  38. ADT Specification Example (Properties) TYPE TimeType DOMAIN Each TimeType value is a time in hours, minutes, and seconds. OPERATIONS Set the time Print the time Increment by one second Compare 2 times for equality Determine if one time is “less than” another Notice NO Implementation given!!

  39. Another ADT Specification TYPE ComplexNumberType DOMAIN Each value is an ordered pair of real numbers (a, b) representing a + bi. OPERATIONS Initialize the complex number Write the complex number Add Subtract Multiply Divide Determine the absolute value of a complex number Notice NO Implementation given!!

  40. ADT Implementation means • choosing a specific data representation for the abstract data using data types that already exist (built-in or programmer-defined) • writing functions for each allowable operation

  41. “10” “45” “27” 10 45 27 Several Possible Representations of TimeType 3 int variables 3 strings 3-element int array • actual choice of representation depends on time, space, and algorithms needed to implement operations 10 45 27

  42. Some Possible Representationsof ComplexNumberType struct with 2 float members 2-element float array -16.2 5.8 .real .imag -16.2 5.8

  43. Classes

  44. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool

  45. Class • A structured type • (many components, access to each) • in a programming language • used to represent an ADT • Not a passive data structure • (only being acted upon) • An active data structure • containing data & operations • in a single unit

  46. class TimeType Specification // SPECIFICATION FILE ( timetype.h ) class TimeType// declares a class data type {// does not allocate memory public : // 5 public function members void Set (int hours ,int mins , int secs ) ; void Increment ( ) ; void Write ( ) const ; bool Equal ( TimeType otherTime ) const ; bool LessThan (TimeType otherTime ) const ; private : // 3 private data members int hrs ; int mins ; int secs ; } ;

  47. Use of C++ data Type class • facilitates re-use of C++ code for an ADT • software that uses the class is called a client • variables of the class type are called class objects or class instances • client code uses public member functions to handle its class objects

  48. Client Code UsingTimeType #include “timetype.h” // includes specification of the class using namespace std ; int main ( ) { TimeType currentTime ; // declares 2 objects of TimeType TimeType endTime ; bool done = false ; currentTime.Set ( 5, 30, 0 ) ; endTime.Set ( 18, 30, 0 ) ; while ( ! done ) { . . . currentTime.Increment ( ) ; if ( currentTime.Equal ( endTime ) ) done = true ; } ; }

  49. class type Definition The class definition creates a data type and names the members of the class. It does not allocate memory for any variables of that type! Client code still needs to declare class variables.

  50. C++ Data Type class represents an ADT • 2 kinds of class members: data members and function members • class members are private by default • data members are generally private • function members are generally declared public • private class members can be accessed only by the class member functions (and friend functions), not by client code.

More Related