Download presentation
Presentation is loading. Please wait.
Published byJayson Harrington Modified over 9 years ago
1
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Data Abstraction and Object-Oriented Design Problem Solving, Abstraction, and Design using C++ 6e by Frank L. Friedman and Elliot B. Koffman
2
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 11.1 Template Classes Enables class to be used with any data type E.g., before class definition, add template where T is a placeholder for the actual type of the class used when a class object is declared
3
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3 Header File for Template Class dummy #ifndef DUMMY_H #define DUMMY_H template class dummy { public: dummy (); // CONSTRUCTOR void setItem (const T&); // STORES A VALUE OF TYPE T void getItem () const; // RETRIEVES A VALUE OF TYPE T private: T value; bool defined; }; #endif // DUMMY_H
4
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4 Template Class Syntax Form:template class className { public:... private:... };
5
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5 Object Declarations & Templates Form: class-name object; –E.g. indexList intList; type can be any defined data type class-name is name of template class object is what is created of type dummy numDepend; dummy spouseName;
6
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6 Listing 11.1 Template class dummy // File: dummy.h // Header file for template class dummy #ifndef DUMMY_H #define DUMMY_H template class dummy { public: // constructor dummy(); // Stores a value of type T void setItem(const T&); // IN: the value to be stored // Retrieves a value of type t T getItem() const; // OUT: returns the value stored private: T item; // Storage for a value of type T bool defined; // Indicates whether item is defined }; #endif // DUMMY_H
7
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7 #include "dummy.h" #include using namespace std; int main() { dummy numDepend; dummy spouseName; int num; string name; numDepend.setItem(2); spouseName.setItem("Caryn"); num = numDepend.getItem(); name = spouseName.getItem(); cout << num << endl; cout << name << endl; return 0; } Listing 11.2 Driver function for template class dummy
8
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8 // File: dummyFun.h // Definition file for template class dummy with // functions #include using namespace std; #ifndef DUMMY_FUN_H #define DUMMY_FUN_H Listing 11.3 Template class dummy with member functions
9
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 template class dummy { public: // constructor dummy()// No value stored yet { defined = false; } // Stores a value of type t void setItem(const T& aVal)// IN: the value to store { item = aVal; defined = true; } Listing 11.3 Template class dummy with member functions cont’d
10
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 // Retrieves a value of type t T getItem() const { if (defined) return item; else cerr << "Error - no value stored!" << endl; } private: T item; bool defined; }; #endif // DUMMY_FUN_H Listing 11.3 Template class dummy with member functions cont’d
11
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11 // File: dummy.cpp // Implementation file for template class dummy #include "dummy.h" #include using namespace std; // constructor template dummy ::dummy() { defined = false; // No value stored yet } // Stores a value of type t template void dummy ::setItem(const T& aVal) { item = aVal; defined = true; } Listing 11.4 Implementation of template class dummy
12
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12 // Retrieves a value of type t template T dummy ::getItem() const { if (defined) return item; else cerr << “Error - no value stored!” << endl; } Listing 11.4 Implementation of template class dummy (cont’d)
13
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13 Key Issues template is a prefix to each function heading Also, dummy :: is used to let the compiler know that the function being defined is a member of a template class –class dummy with parameter T
14
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14 11.2 The Indexed List Abstract Data Type Some deficiencies with arrays in C++ –Can be overwritten –Must track the size of the array filled or some empty spots –Must write own functions to locate various things in arrays find smallest, find largest etc. Indexed list implemented as a template class can overcome these deficiencies
15
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15 Specifications for Indexed List Class Attributes –elementsArray of data items –int sizeCount of items
16
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16 Member Functions for Indexed List Class indexListappend insertreplace retrieveremove findMinfindMax searchsort readdisplay getSize
17
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17 // File IndexList.h // Definition of indexed list template class #ifndef INDEXLIST_H #define INDEXLIST_H #include using namespace std; template class indexList { public: // Constructor indexList (); // Add an item to the end of an indexed list bool append (const T&);// IN: item appended // Replace an element at a specified index bool replace (int, // IN: index const T&);// IN: item inserted Listing 11.5 Class indexList header file
18
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18 // Insert an element at a specified index bool insert (int, const T&); // Retrieve an element at a specified index bool retrieve (int, T&) const; // Delete an element at a specified index bool remove (int); // Find index of smallest value in a sublist int findMin (int, int) const; // Find index of largest value in a sublist int findMax (int, int) const; // Find index of a target item // Returns -1 if target item not found int search (const T&) const; Listing 11.5 Class indexList header file (continued)
19
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19 // Sort an indexed list void selSort ( ); // Read data into the list void read (istream &); // Write the list contents to an output stream void display (ostream& outs) const; // Get the current size int getSize ( ) const; //Data Members T elements[maxSize]; int size; }; #endif // INDEXLIST_H Listing 11.5 Class indexList header file (continued)
20
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20 Using the indexList Class Like a user-friendly array Create a list indexList myIntData; indexList myStringData; Find something in the list myIntData.retrieve (0, anInt);
21
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21 Listing 11.6 Testing class indexList
22
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 22 Listing 11.6 Testing class indexList (continued)
23
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23 Listing 11.6 Testing class indexList (continued)
24
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 11.5 Implementing the Indexed List Class Provides details of the indexed list class Note that each function begins with template Note that each function contains the class name and scope resolution operator indexList ::
25
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25 Listing 11.7 indexList.cpp // File: indexList.cpp // Indexed list class implementation #include "indexList.h" #include using namespace std; template indexList ::indexList() // constructor { size = 0;// list is empty } // Add an item to the end of an indexed list template bool indexList ::append(const T& item) // Pre: item is defined // Post: if size < maxSize, item is appended to list // Returns: true if item was appended; otherwise, false { bool result;
26
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 26 Listing 11.7 indexList.cpp cont’d // Add item to the end of the list if list is not full. if (size < maxSize) { elements[size] = item; size++; result = true; } else { cerr << "*** Array is filled - can't append!" << endl; result = false; } return result; } // Replace an item at a specified index with a new one. // Returns: true if item was inserted; otherwise, false template bool indexList ::replace(int index, const T& item) { bool result;
27
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 27 Listing 11.7 indexList.cpp cont’d // Overwrite a list element if index is valid. if (index >= 0 && index < size) { elements[index] = item; result = true; } else { cerr << "*** Index " << index << " not in filled part" << " - can't insert!" << endl; result = false; } return result; } template bool indexList ::insert(int index, const T& item) { bool result; int i;
28
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28 Listing 11.7 indexList.cpp cont’d // Insert a list element if index is valid. if (index >= 0 && index < size && size < maxSize) { // Shift elements down 1 position for (i = size - 1; i >= index; i--) elements[i + 1] = elements[i]; elements[index] = item; // insert size++; result = true; } else { cerr << "*** Index " << index << " not in filled part" << " - can't insert!" << endl; result = false; } return result; }
29
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29 Listing 11.7 indexList.cpp cont’d // Retrieve an item at a specified index // Post: if index is valid, elements[index] is returned template bool indexList ::retrieve(int index, T& item) const { bool result; // Return a list element through item if index is valid. if (index >= 0 && index < size) { item = elements[index]; result = true; } else { cerr << "*** Index " << index << " not in filled part" << " - can't retrieve!" << endl; result = false; } return result; }
30
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 30 Listing 11.7 indexList.cpp cont’d // Delete an element at a specified index by shifting elements template bool indexList ::remove(int index) { bool result; int i; // Delete element at index i by moving elements up if (index >= 0 && index < size) { for (i = index + 1; i < size; i++) elements[i-1] = elements[i]; size--; // Decrement size result = true; } else { cerr << "*** Index " << index << " not in filled part" << " - can't delete!" << endl; result = false; } return result; }
31
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31 Listing 11.7 indexList.cpp cont’d // Read data into the list and set size to number read template void indexList ::read(istream& ins) { int numItems;// input - number of items to read T nextItem;// input - next data item cout << "Enter number of list items to read: "; ins >> numItems; ins.ignore(80, '\n'); // skip newline // If numItems is valid, read each list element, // starting with first element. size = 0; // The list is empty. if (numItems >= 0 && numItems <= maxSize) while (size < numItems) { cout << "Enter next item - "; ins >> nextItem; elements[size] = nextItem; size++; } else cerr << "*** Number of items " << numItems << " is invalid - data entry is cancelled!" << endl; }
32
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32 Listing 11.7 indexList.cpp cont’d // Write all list elements to an output stream template void indexList ::display(ostream@ outs) const { // Display each list element. for (int i = 0; i < size; i++) outs << elements[i] << endl; } // Find index of a target item // Pre: none // Post: Returns the index of target if found; // otherwise, return -1. template int indexList ::search(const T& target) const { for (int i = 0; i < maxSize; i++) if (elements[i] == target) return i; // target found at position i // target not found return -1; }
33
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Listing 11.7 indexList.cpp cont’d // Get the current size template int indexList ::getSize() const { return size; } // Sort the indexed list template void indexList ::selSort() { // Selection sort stub - do nothing }
34
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34 11.4 Illustrating Object-Oriented Design 1. Identify objects and define services provided by each 2. Identify interactions among objects in terms of services required or provided 3. Determine the specification of each object 4. Implement each object
35
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35 Case Study: Telephone Directory We’ve been asked to design a program to store and retrieve a growing collection of names and telephone numbers in a telephone directory. We create an initial directory by reading a list of names and numbers of people called frequently. The directory program should also be able to insert new names and numbers, change numbers, retrieve selected numbers, and delete names and numbers.
36
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36 Specification for a Directory Entry Attributes –string name –string number Member Functions –entrysetEntry –getNamegetNumber Operations = =,, >
37
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37 Header file for a directory entry
38
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 38 Header file for a directory entry (continued)
39
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 39 // File: entry.cpp // Implementation file for class entry #include “entry.h” #include <iostream? #include using namespace std; // constructor entry::entry() { name = “”; number = “”; } // Store data in an entry void entry::setEntry(const string& na,// IN: name const string& nr)// IN: number { name = na; number = nr; } Class entry implementation
40
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 40 // Get name string entry::getName() const { return name; } // Get number string entry::getNumber() const { return number; } // Operators bool entry::operator == (const entry& dE) // IN: right-operand { return (name == dE.name); } bool entry::operator < (const entry& dE) // IN: right-operand { return (name < dE.name); } Class entry implementation (continued)
41
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 41 bool entry::operator > (const entry& dE) // IN: right-operand { return (name > dE.name); } // friends ostream& operator << (ostream& outs, // INOUT: stream const entry& dE) // IN: entry displayed { outs << “Name is “ << dE.name << endl; outs << “Number is “ << dE.number << endl; return outs; } istream& operator >> (istream& ins, // INOUT: stream entry& dE) // OUT: entry read { cout << “Enter name: “; getline(ins, dE.name, ‘\n’; cout << “Enter number: “; ins >> dE.number; return ins; } Class entry implementation (continued)
42
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 42 Using a Telephone Directory Data Requirements –Problem Input telDirec char choice –Problem Output telDirec
43
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 43 Case Study: Algorithm 1. Read the initial directory 2. Do 2.1 Display the menu 2.2 Read the user’s selection 2.3 Perform the operation selected while the user is not done
44
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 44 Analysis and Design for select Data Requirements –Input Argument char choice –Input/Output Argument telDirec –Local Variables entry anEntry string aName int index
45
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 45 Algorithm for select Choose one of the cases listed below: Case ‘A’: Read the entry to add Append it to the directory Case ‘C’: Read the modified entry Search for its name in the directory if the name is found Replace current entry at index position else Append entry to directory if user approves
46
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 46 Algorithm for select (con’t) Case ‘D’: Read the name of entry to delete Search for the name in the directory if the name is found delete the entry Case ‘G’: Read the name of the entry to retrieve Search for the name in the directory if the name is found Retrieve the entry Retrieve and display the entry’s number attribute
47
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 47 Algorithm for select (con’t) Case ‘S’: Call the sort function Case ‘P’: Call the display function Case ‘Q’: Do nothing
48
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 48 Menu-driven program for telephone directory
49
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 49 Menu-driven program for telephone directory (continued)
50
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 50 Menu-driven program for telephone directory (continued)
51
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 51 Menu-driven program for telephone directory (continued)
52
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 52 Menu-driven program for telephone directory (continued)
53
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53 Menu-driven program for telephone directory (continued)
54
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 54 Sample Run Enter the initial directory entries - Enter the number of list items to read: 1 Enter the next item - Enter name: Maria Sanchez Enter number: 215-555-1234 Enter your choice - A(add), C(change), D(delete), G(get), S(sort), P(print), Q(quit):...
55
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 55 11.5 Operator Overloading and Friends More than one way to provide operator functions for class objects –overloading existing operators, such as, << allows relation of the form e1 < e2 –pass second object to first object’s lessThan member function e1.lessThan(e2); –use friend function to implement operation lessThan(e1,e2);
56
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 56 Operator Overloading E.g. in entry class definition file bool operator < (const entry&); < is an operator that can be applied to a type entry object The parameter list indicates that the right operand of < must also be of type entry
57
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57 Class entry operator <
58
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 58 Friends A friend of a class is a member function or operator that has two or more operands from the class being defined or an operand from another class –has all privileges of member function –can’t be const function E.g. in entry class definition file friend bool lessThan(const entry& e1, const entry& e2); Note absence of entry:: in function lessThan –lessThan isn’t a member function of class entry
59
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 59 Overloading Operator with Operands from Different Classes E.g. ins >> anEntry; outs << anEntry; Declare > as friends of entry class friend ostream& operator << (ostream&, const entry&); friend istream& operator >> (istream&, entry&);
60
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 60 Friend Function (Operator) Declaration Form friend result-type function-name (argument-list); friend result-type operator op-symbol (argument-list); E.g. friend bool equals (const entry&, const entry&); friend bool operator = = (const entry&, const entry&);
61
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 61 11.6 The vector Class Standard Template Library (STL) provides a number of container classes E.g. vector –similar to indexed list class –size of vector can increase/decrease as needed –elements can be added/deleted from end –elements can be inserted into middle –proper use of at and size functions help prevent subscript range errors
62
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 62 Vectors Must include library #include Declare a vector like any object of template class vector vector-name(size); E.g. vector intVec(10); vector hours(5. 0.5); vector telDirec;
63
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 63 Accessing vector Elements Use subscript notation the same way as with arrays sum = 0; for (int i=0; i < intVec.size( ); i++) { sum += intVec[i]; } Or, use at function to access each element with index checking sum += intVec.at(i); // instead of sum += intVec[i];
64
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 64 Some vector Member Functions int size( ) const T at(int) const T front( ) T back( ) void push_back(const T&) void pop_back(int) void resize(int)
65
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 65 Accessing a Vector through an Iterator Iterator –a pointer-like type that references elements of a container –used to navigate through a container object Declaration vector ::iterator index; Use for (index = myValues.begin( ); index != myFalues.end( ); index++) cout << *index << endl;
66
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 66 Member Functions for vector Class with Iterators iterator begin( ) iterator end( ) void insert(iterator, T) void erase(iterator)
67
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 67 Standard Algorithms C++ provides a library of algorithms for use on certain container classes –E.g. search, sort Insert algorithm header #include E.g. sort(myValues.begin( ), myValues.end( )); index = find(myValues.begin( ), myValues.end( ), target);
68
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 68 11.7 Common Programming Errors Subscript range errors Improper use of brackets Misuse of subscript notation or dot notation Errors in defining template classes Errors in using friend functions
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.