Documents Found!
As seen in
Less Work, Better Grades
Join
Course Hero
Access
best resources
Ace
your classes
Ace your courses with Course Hero!

Limited, unformatted preview (showing 56 of 6197 words):
...Chapter 1 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3 Restrictions on Operator Overloading 8.4 Operator Functions as Class Members vs. as friend Functions 8.5 Overloading Stream-Insertion and Stream-Extraction Operators 8.6 Overloading Unary Operators 8.7 Overloading Binary Operators 8.8 Case Study: Array Class 8.9 Converting between Types 8.10 Case Study: A String Class 8.11 Overloading ++ and -8.12 Case Study: A Date Class 8.13 Standard Library...
Study Smarter, Score Higher
 
Document Content (unformatted)
Course Hero has millions of student submitted documents similar to the one below including study guides, homework solutions, papers, exam answer keys and textbook solutions.
Chapter 1 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3 Restrictions on Operator Overloading 8.4 Operator Functions as Class Members vs. as friend Functions 8.5 Overloading Stream-Insertion and Stream-Extraction Operators 8.6 Overloading Unary Operators 8.7 Overloading Binary Operators 8.8 Case Study: Array Class 8.9 Converting between Types 8.10 Case Study: A String Class 8.11 Overloading ++ and -8.12 Case Study: A Date Class 8.13 Standard Library Classes string and vector 2003 Prentice Hall, Inc. All rights reserved. 2 8.1 Introduction Use operators with objects (operator overloading) Clearer than function calls for certain classes Operator sensitive to context Examples << Stream insertion, bitwise left-shift + Performs arithmetic on multiple types (integers, floats, etc.) Will discuss when to use operator overloading 2003 Prentice Hall, Inc. All rights reserved. 8.2 Fundamentals of Operator Overloading Types Built in (int, char) or user-defined Can use existing operators with user-defined types Cannot create new operators 3 Overloading operators Create a function for the class Name function operator followed by symbol Operator+ for the addition operator + 2003 Prentice Hall, Inc. All rights reserved. 8.2 Fundamentals of Operator Overloading Using operators on a class object It must be overloaded for that class Exceptions: Assignment operator, = Memberwise assignment between objects Address operator, & Returns address of object Both can be overloaded 4 Overloading provides concise notation object2 = object1.add(object2); object2 = object2 + object1; 2003 Prentice Hall, Inc. All rights reserved. 8.3 Restrictions on Operator Overloading Cannot change How operators act on built-in data types I.e., cannot change integer addition 5 Precedence of operator (order of evaluation) Use parentheses to force order-of-operations Associativity (left-to-right or right-to-left) Number of operands & is unitary, only acts on one operand Cannot create new operators Operators must be overloaded explicitly Overloading + does not overload += 2003 Prentice Hall, Inc. All rights reserved. 8.3 Restrictions on Operator Overloading Operators that can be overloaded + ~ /= <<= -new[] ! %= == ->* delete[] * = ^= != , / < &= <= -> % > |= >= [] ^ += << && () & -= >> || new | *= >>= ++ delete 6 Operators that cannot be overloaded . .* :: ?: sizeof 2003 Prentice Hall, Inc. All rights reserved. 8.4 Operator Functions As Class Members Vs. As Friend Functions Operator functions Member functions Use this keyword to implicitly get argument Gets left operand for binary operators (like +) Leftmost object must be of same class as operator 7 Non member functions Need parameters for both operands Can have object of different class than operator Must be a friend to access private or protected data Called when Left operand of binary operator of same class Single operand of unitary operator of same class 2003 Prentice Hall, Inc. All rights reserved. 8.4 Operator Functions As Class Members Vs. As Friend Functions Overloaded << operator Left operand of type ostream & Such as cout object in cout << classObject 8 Similarly, overloaded >> needs istream & Thus, both must be non-member functions 2003 Prentice Hall, Inc. All rights reserved. 8.4 Operator Functions As Class Members Vs. As Friend Functions Commutative operators May want + to be commutative So both a + b and b + a work 9 Suppose we have two different classes Overloaded operator can only be member function when its class is on left HugeIntClass + Long int Can be member function When other way, need a non-member overload function Long int + HugeIntClass 2003 Prentice Hall, Inc. All rights reserved. 8.5 Overloading Stream-Insertion and Stream-Extraction Operators << and >> Already overloaded to process each built-in type Can also process a user-defined class 10 Example program Class PhoneNumber Holds a telephone number Print out formatted number automatically (123) 456-7890 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8.3: fig08_03.cpp // Overloading the stream-insertion and // stream-extraction operators. #include <iostream> using using using using using std::cout; std::cin; std::endl; std::ostream; std::istream; Outline fig08_03.cpp (1 of 3) 11 #include <iomanip> using std::setw; Notice function prototypes for overloaded operators >> and << // PhoneNumber class definition They must be non-member friend class PhoneNumber { functions, since the object of class friend ostream &operator<<( ostream&, const PhoneNumber & ); Phonenumber appears on the right friend istream &operator>>( istream&, PhoneNumber & ); of the operator. private: char areaCode[ 4 ]; char exchange[ 4 ]; char line[ 5 ]; // 3-digit area code and null cout >> object // 3-digit exchange and null // 4-digit line and null cin << object }; // end class PhoneNumber 2003 Prentice Hall, Inc. All rights reserved. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // overloaded stream-insertion operator; cannot be // a member function if we would like to invoke it with // cout << somePhoneNumber; fig08_03.cpp ostream &operator<<( ostream &output, const PhoneNumber &num ) (2 of 3) { The expression: output << "(" << num.areaCode << ") " cout << phone; << num.exchange << "-" << num.line; return output; // enables cout << a << b << c; Outline 12 is interpreted as the function call: operator<<(cout, phone); output is an alias for cout. } // end function operator<< // overloaded stream-extraction operator; cannot beThis allows objects to be cascaded. // a member function if we would like to invoke it cout << phone1 << phone2; with ignore() skips specified // cin >> somePhoneNumber; first calls number of characters from istream &operator>>( istream &input, PhoneNumber &num ) operator<<(cout, phone1), and input (1 by default). { returns cout. input.ignore(); // skip ( input >> setw( 4 ) >> num.areaCode; // input area code Next, cout << phone2 executes. input.ignore( 2 ); // skip ) and space input >> setw( 4 ) >> num.exchange;Stream manipulator setw // input exchange input.ignore(); // skip dash of restricts number(-) characters input >> setw( 5 ) >> num.line; // setw(4) read.input line allows 3 return input; // enables cin characters to be read, leaving >> a >> b the null character. room for >> c; 2003 Prentice Hall, Inc. All rights reserved. 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 } // end function operator>> int main() { PhoneNumber phone; // create object phone cout << "Enter phone number in the form (123) 456-7890:\n"; // cin >> phone invokes operator>> by implicitly issuing // the non-member function call operator>>( cin, phone ) cin >> phone; cout << "The phone number entered was: " ; // cout << phone invokes operator<< by implicitly issuing // the non-member function call operator<<( cout, phone ) cout << phone << endl; return 0; } // end main Outline fig08_03.cpp (3 of 3) fig08_03.cpp output (1 of 1) 13 Enter phone number in the form (123) 456-7890: (800) 555-1212 The phone number entered was: (800) 555-1212 2003 Prentice Hall, Inc. All rights reserved. 14 8.6 Overloading Unary Operators Overloading unary operators Non-static member function, no arguments Non-member function, one argument Argument must be class object or reference to class object Remember, static functions only access static data 2003 Prentice Hall, Inc. All rights reserved. 15 8.6 Overloading Unary Operators Upcoming example (8.10) Overload ! to test for empty string If non-static member function, needs no arguments !s becomes s.operator!() class String { public: bool operator!() const; ... }; If non-member function, needs one argument s! becomes operator!(s) class String { friend bool operator!( const String & ) ... } 2003 Prentice Hall, Inc. All rights reserved. 16 8.7 Overloading Binary Operators Overloading binary operators Non-static member function, one argument Non-member function, two arguments One argument must be class object or reference Upcoming example If non-static member function, needs one argument class String { public: const String &operator+=( const String & ); ... }; y += z equivalent to y.operator+=( z ) 2003 Prentice Hall, Inc. All rights reserved. 17 8.7 Overloading Binary Operators Upcoming example If non-member function, needs two arguments Example: class String { friend const String &operator+=( String &, const String & ); ... }; y += z equivalent to operator+=( y, z ) 2003 Prentice Hall, Inc. All rights reserved. 18 8.8 Case Study: Array class Arrays in C++ No range checking Cannot be compared meaningfully with == No array assignment (array names const pointers) Cannot input/output entire arrays at once One element at a time Example:Implement an Array class with Range checking Array assignment Arrays that know their size Outputting/inputting entire arrays with << and >> Array comparisons with == and != 2003 Prentice Hall, Inc. All rights reserved. 19 8.8 Case Study: Array class Copy constructor Used whenever copy of object needed Passing by value (return value or parameter) Initializing an object with a copy of another Array newArray( oldArray ); newArray copy of oldArray Prototype for class Array Array( const Array & ); Must take reference Otherwise, pass by value Tries to make copy by calling copy constructor Infinite loop 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8.4: array1.h // Array class for storing arrays of integers. #ifndef ARRAY1_H #define ARRAY1_H #include <iostream> using std::ostream; using std::istream; class Array { friend ostream &operator<<( ostream &, const Array & ); friend istream &operator>>( istream &, Array & ); public: Array( int = 10 ); Array( const Array & ); ~Array(); int getSize() const; Outline array1.h (1 of 2) 20 // // // // return size Most operators overloaded as member default constructor functions (except << and >>, which must be noncopy constructor destructor member functions). Prototype for copy constructor. // assignment operator const Array &operator=( const Array & ); // equality operator bool operator==( const Array & ) const; 2003 Prentice Hall, Inc. All rights reserved. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // inequality operator; returns opposite of == operator bool operator!=( const Array &right ) const { return ! ( *this == right ); // invokes Array::operator== } // end function operator!= // subscript operator for int &operator[]( int ); Outline array1.h (2 of 2) 21 != operator simply returns opposite of == operator. non-const objects returns lvalue Thus, only need to define the == operator. // subscript operator for const objects returns rvalue const int &operator[]( int ) const; private: int size; // array size int *ptr; // pointer to first element of array }; // end class Array #endif 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig 8.5: array1.cpp // Member function definitions for class Array #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setw; #include <new> #include <cstdlib> #include "array1.h" // C++ standard "new" operator // exit function prototype // Array class definition Outline array1.cpp (1 of 7) 22 // default constructor for class Array (default size 10) Array::Array( int arraySize ) { // validate arraySize size = ( arraySize > 0 ? arraySize : 10 ); ptr = new int[ size ]; // create space for array 2003 Prentice Hall, Inc. All rights reserved. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 for ( int i = 0; i < size; i++ ) ptr[ i ] = 0; // initialize array } // end Array default constructor // copy constructor for class Array; // must receive a reference to prevent infinite recursion We must declare a new integer array Array::Array( const Array &arrayToCopy ) the objects do not point to the same : size( arrayToCopy.size ) memory. { ptr = new int[ size ]; // create space for array for ( int i = 0; i < size; i++ ) ptr[ i ] = arrayToCopy.ptr[ i ]; } // end Array copy constructor // destructor for class Array Array::~Array() { delete [] ptr; // reclaim array space } // end destructor Outline array1.cpp (2 of 7) so 23 // copy into object 2003 Prentice Hall, Inc. All rights reserved. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 // return size of array int Array::getSize() const { return size; } // end function getSize // overloaded assignment operator;Want to avoid self-assignment. // const return avoids: ( a1 = a2 ) = a3 const Array &Array::operator=( const Array &right ) { if ( &right != this ) { // check for self-assignment // for arrays of different sizes, deallocate original // left-side array, then allocate new left-side array if ( size != right.size ) { delete [] ptr; // reclaim space size = right.size; // resize this object ptr = new int[ size ]; // create space for array copy } // end inner if for ( int i = 0; i < size; i++ ) ptr[ i ] = right.ptr[ i ]; // copy array into object } // end outer if Outline array1.cpp (3 of 7) 24 2003 Prentice Hall, Inc. All rights reserved. 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 return *this; // enables x = y = z, for example Outline array1.cpp (4 of 7) 25 } // end function operator= // determine if two arrays are equal and // return true, otherwise return false bool Array::operator==( const Array &right ) const { if ( size != right.size ) return false; // arrays of different sizes for ( int i = 0; i < size; i++ ) if ( ptr[ i ] != right.ptr[ i ] ) return false; // arrays are not equal return true; // arrays are equal } // end function operator== 2003 Prentice Hall, Inc. All rights reserved. 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 // overloaded subscript operator for non-const Arrays // reference return creates an lvalue int &Array::operator[]( int subscript ) { // check for subscript out of range error if ( subscript < 0 || subscript >= size integers1[5] calls ){ integers1.operator[]( cout << "\nError: Subscript " << subscript << " out of range" << endl; exit( 1 ); } // end if // terminate program; subscript out of range Outline array1.cpp (5 of 7) 5) 26 exit() (header <cstdlib>) ends the program. return ptr[ subscript ]; // reference return } // end function operator[] 2003 Prentice Hall, Inc. All rights reserved. 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 // overloaded subscript operator for const Arrays // const reference return creates an rvalue const int &Array::operator[]( int subscript ) const { // check for subscript out of range error if ( subscript < 0 || subscript >= size ) { cout << "\nError: Subscript " << subscript << " out of range" << endl; exit( 1 ); } // end if return ptr[ subscript ]; // const reference return } // end function operator[] // overloaded input operator for class Array; // inputs values for entire array istream &operator>>( istream &input, Array &a ) { for ( int i = 0; i < a.size; i++ ) input >> a.ptr[ i ]; return input; } // end function // enables cin >> x >> y; // terminate program; subscript out of range Outline array1.cpp (6 of 7) 27 2003 Prentice Hall, Inc. All rights reserved. 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 // overloaded output operator for class Array ostream &operator<<( ostream &output, const Array &a ) { int i; // output private ptr-based array for ( i = 0; i < a.size; i++ ) { output << setw( 12 ) << a.ptr[ i ]; if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output output << endl; } // end for if ( i % 4 != 0 ) // end last line of output output << endl; return output; // enables cout << x << y; Outline array1.cpp (7 of 7) 28 } // end function operator<< 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 8.6: fig08_06.cpp // Array class test program. #include <iostream> using std::cout; using std::cin; using std::endl; #include "array1.h" int main() { Array integers1( 7 ); Array integers2; Outline fig08_06.cpp (1 of 3) 29 // seven-element Array // 10-element Array by default // print integers1 size and contents cout << "Size of array integers1 is " << integers1.getSize() << "\nArray after initialization:\n" << integers1; // print integers2 size and contents cout << "\nSize of array integers2 is " << integers2.getSize() << "\nArray after initialization:\n" << integers2; 2003 Prentice Hall, Inc. All rights reserved. 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // input and print integers1 and integers2 cout << "\nInput 17 integers:\n"; cin >> integers1 >> integers2; cout << "\nAfter input, the arrays contain:\n" << "integers1:\n" << integers1 << "integers2:\n" << integers2; // use overloaded inequality (!=) operator cout << "\nEvaluating: integers1 != integers2\n"; if ( integers1 != integers2 ) cout << "integers1 and integers2 are not equal\n"; // create array integers3 using integers1 as an // initializer; print size and contents Array integers3( integers1 ); // calls copy constructor cout << "\nSize of array integers3 is " << integers3.getSize() << "\nArray after initialization:\n" << integers3; Outline fig08_06.cpp (2 of 3) 30 2003 Prentice Hall, Inc. All rights reserved. 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 // use overloaded assignment (=) operator cout << "\nAssigning integers2 to integers1:\n"; integers1 = integers2; // note target is smaller cout << "integers1:\n" << integers1 << "integers2:\n" << integers2; // use overloaded equality (==) operator cout << "\nEvaluating: integers1 == integers2\n"; if ( integers1 == integers2 ) cout << "integers1 and integers2 are equal\n"; // use overloaded subscript operator to create rvalue cout << "\nintegers1[5] is " << integers1[ 5 ]; // use overloaded subscript operator to create lvalue cout << "\n\nAssigning 1000 to integers1[5]\n"; integers1[ 5 ] = 1000; cout << "integers1:\n" << integers1; // attempt to use out-of-range subscript cout << "\nAttempt to assign 1000 to integers1[15]" << endl; integers1[ 15 ] = 1000; // ERROR: out of range return 0; } // end main Outline fig08_06.cpp (3 of 3) 31 2003 Prentice Hall, Inc. All rights reserved. Size of array integers1 is 7 Array after initialization: 0 0 0 0 0 0 Size of array integers2 is 10 Array after initialization: 0 0 0 0 0 0 0 0 Input 17 integers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 After input, the arrays contain: integers1: 1 2 3 5 6 7 integers2: 8 9 10 12 13 14 Outline 0 32 fig08_06.cpp output (1 of 3) 0 0 4 11 15 2003 Prentice Hall, Inc. All rights reserved. Evaluating: integers1 != integers2 integers1 and integers2 are not equal Size of array integers3 is 7 Array after initialization: 1 2 3 5 6 7 Assigning integers2 to integers1: integers1: 8 9 10 12 13 14 16 17 integers2: 8 9 10 12 13 14 16 17 Evaluating: integers1 == integers2 integers1 and integers2 are equal integers1[5] is 13 Outline fig08_06.cpp output (2 of 3) 33 4 11 15 11 15 2003 Prentice Hall, Inc. All rights reserved. Assigning 1000 to integers1[5] integers1: 8 9 10 12 1000 14 16 17 Attempt to assign 1000 to integers1[15] Error: Subscript 15 out of range Outline 11 15 34 fig08_06.cpp output (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 35 8.9 Converting between Types Casting Traditionally, cast integers to floats, etc. May need to convert between user-defined types Cast operator (conversion operator) Convert from One class to another Class to built-in type (int, char, etc.) Must be non-static member function Cannot be friend Do not specify return type Implicitly returns type to which you are converting 2003 Prentice Hall, Inc. All rights reserved. 36 8.9 Converting between Types Example Prototype A::operator char *() const; Casts class A to a temporary char * (char *)s calls s.operator char*() Also A::operator int() const; A::operator OtherClass() const; 2003 Prentice Hall, Inc. All rights reserved. 37 8.9 Converting between Types Casting can prevent need for overloading Suppose class String can be cast to char * cout << s; // s is a String Compiler implicitly converts s to char * Do not have to overload << Compiler can only do 1 cast 2003 Prentice Hall, Inc. All rights reserved. 38 8.10 Case Study: A String Class Build class String String creation, manipulation Class string in standard library (more Chapter 15) Conversion constructor Single-argument constructor Turns objects of other types into class objects String s1( hi ); Creates a String from a char * Any single-argument constructor is a conversion constructor 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8.7: string1.h // String class definition. #ifndef STRING1_H #define STRING1_H #include <iostream> using std::ostream; using std::istream; class String { friend ostream &operator<<( ostream &, const String & ); Conversion constructor friend istream &operator>>( istream &, String & ); public: String( const char * = "" ); // conversion/default ctor String( const String & ); // copy constructor s1 += s2 ~String(); // destructor Outline string1.h (1 of 3) 39 to make a String from a char *. interpreted as s1.operator+=(s2) const String &operator=( const String & ); // assignment Can also concatenate const String &operator+=( const String & ); // concatenation bool operator!() const; // bool operator==( const String & ) const; // bool operator<( const String & ) const; // a String and a char * because the is String will cast the char * compiler empty? test s1 == to a String. argument s2 test s1 < s2 can only do 1 level However, it of casting. 2003 Prentice Hall, Inc. All rights reserved. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // test s1 != s2 bool operator!=( const String & right ) const { return !( *this == right ); } // end function operator!= // test s1 > s2 bool operator>( const String &right ) const { return right < *this; } // end function operator> // test s1 <= s2 bool operator<=( const String &right ) const { return !( right < *this ); } // end function operator <= // test s1 >= s2 bool operator>=( const String &right ) const { return !( *this < right ); } // end function operator>= Outline string1.h (2 of 3) 40 2003 Prentice Hall, Inc. All rights reserved. 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 char &operator[]( int ); // const char &operator[]( int ) const; // String operator()( int, int ); int getLength() const; private: int length; char *sPtr; Two overloaded subscript subscript operator operators, for const and subscript operator non-const objects. Outline string1.h (3 of 3) 41 // return a substring // return string length Overload the function call operator () to return a substring. This operator can have any amount of operands. // utility function // string length // pointer to start of string void setString( const char * ); }; // end class String #endif 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 // Fig. 8.8: string1.cpp // Member function definitions for class String. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; #include <new> #include <cstring> #include <cstdlib> #include "string1.h" // C++ standard "new" operator // strcpy and strcat prototypes // exit prototype // String class definition Outline string1.cpp (1 of 8) 42 // conversion constructor converts char * to String String::String( const char *s ) : length( strlen( s ) ) { cout << "Conversion constructor: " << s << '\n'; setString( s ); // call utility function } // end String conversion constructor 2003 Prentice Hall, Inc. All rights reserved. 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 // copy constructor String::String( const String &copy ) : length( copy.length ) { cout << "Copy constructor: " << copy.sPtr << '\n'; setString( copy.sPtr ); // call utility function } // end String copy constructor // destructor String::~String() { cout << "Destructor: " << sPtr << '\n'; delete [] sPtr; // reclaim string } // end ~String destructor // overloaded = operator; avoids self assignment const String &String::operator=( const String &right ) { cout << "operator= called\n"; if ( &right != this ) { delete [] sPtr; length = right.length; setString( right.sPtr ); } // // // // avoid self assignment prevents memory leak new String length call utility function Outline string1.cpp (2 of 8) 43 2003 Prentice Hall, Inc. All rights reserved. 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 else cout << "Attempted assignment of a String to itself\n"; return *this; // enables cascaded assignments Outline string1.cpp (3 of 8) 44 } // end function operator= // concatenate right operand to this object and // store in this object. const String &String::operator+=( const String &right ) { size_t newLength = length right.length; + // new length char *tempPtr = new char[ newLength + 1 ]; // create memory strcpy( tempPtr, sPtr ); strcpy( tempPtr + length, right.sPtr ); delete [] sPtr; sPtr = tempPtr; length = newLength; return *this; // copy sPtr // copy right.sPtr // reclaim old space // assign new array to sPtr // assign new length to length // enables cascaded calls } // end function operator+= 2003 Prentice Hall, Inc. All rights reserved. 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 // is this String empty? bool String::operator!() const { return length == 0; } // end function operator! // is this String equal to right String? bool String::operator==( const String &right ) const { return strcmp( sPtr, right.sPtr ) == 0; } // end function operator== // is this String less than right String? bool String::operator<( const String &right ) const { return strcmp( sPtr, right.sPtr ) < 0; } // end function operator< Outline string1.cpp (4 of 8) 45 2003 Prentice Hall, Inc. All rights reserved. 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 // return reference to character in String as lvalue char &String::operator[]( int subscript ) { // test for subscript out of range if ( subscript < 0 || subscript >= length ) { cout << "Error: Subscript " << subscript << " out of range" << endl; exit( 1 ); } return sPtr[ subscript ]; } // end function operator[] // return reference to character in String as rvalue const char &String::operator[]( int subscript ) const { // test for subscript out of range if ( subscript < 0 || subscript >= length ) { cout << "Error: Subscript " << subscript << " out of range" << endl; exit( 1 ); } return sPtr[ subscript ]; } // end function operator[] // creates rvalue // terminate program // creates lvalue // terminate program Outline string1.cpp (5 of 8) 46 2003 Prentice Hall, Inc. All rights reserved. 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 // return a substring beginning at index and // of length subLength String String::operator()( int index, int subLength ) { // if index is out of range or substring length < 0, // return an empty String object if ( index < 0 || index >= length || subLength < 0 ) return ""; // converted to a String object automatically // determine length of substring int len; if ( ( subLength == 0 ) || ( index + subLength > length ) ) len = length - index; else len = subLength; // allocate temporary array for substring and // terminating null character char *tempPtr = new char[ len + 1 ]; // copy substring into char array and terminate string strncpy( tempPtr, &sPtr[ index ], len ); tempPtr[ len ] = '\0'; Outline string1.cpp (6 of 8) 47 2003 Prentice Hall, Inc. All rights reserved. 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 // create temporary String object containing the substring String tempString( tempPtr ); delete [] tempPtr; // delete temporary array return tempString; // return copy of the temporary String Outline string1.cpp (7 of 8) 48 } // end function operator() // return string length int String::getLength() const { return length; } // end function getLenth // utility function called by constructors and operator= void String::setString( const char *string2 ) { sPtr = new char[ length + 1 ]; // allocate memory strcpy( sPtr, string2 ); // copy literal to object } // end function setString 2003 Prentice Hall, Inc. All rights reserved. 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 // overloaded output operator ostream &operator<<( ostream &output, const String &s ) { output << s.sPtr; return output; // enables cascading Outline string1.cpp (8 of 8) 49 } // end function operator<< // overloaded input operator istream &operator>>( istream &input, String &s ) { char temp[ 100 ]; // buffer to store input input >> setw( 100 ) >> temp; s = temp; // use String class assignment operator return input; // enables cascading } // end function operator>> 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 8.9: fig08_09.cpp // String class test program. #include <iostream> using std::cout; using std::endl; #include "string1.h" int main() { String s1( "happy" ); String s2( " birthday" ); String s3; // test cout << << << << << << << << << overloaded equality and relational operators "s1 is \"" << s1 << "\"; s2 is \"" << s2 "\"; s3 is \"" << s3 << '\"' "\n\nThe results of comparing s2 and s1:" "\ns2 == s1 yields " ( s2 == s1 ? "true" : "false" ) "\ns2 != s1 yields " ( s2 != s1 ? "true" : "false" ) "\ns2 > s1 yields " ( s2 > s1 ? "true" : "false" ) Outline fig08_09.cpp (1 of 4) 50 2003 Prentice Hall, Inc. All rights reserved. 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 << << << << << << "\ns2 < s1 yields " ( s2 < s1 ? "true" : "false" ) "\ns2 >= s1 yields " ( s2 >= s1 ? "true" : "false" ) "\ns2 <= s1 yields " ( s2 <= s1 ? "true" : "false" ); Outline fig08_09.cpp (2 of 4) 51 // test overloaded String empty (!) operator cout << "\n\nTesting !s3:\n"; if ( !s3 ) { cout << "s3 is empty; assigning s1 to s3;\n"; s3 = s1; // test overloaded assignment cout << "s3 is \"" << s3 << "\""; } // test overloaded String concatenation operator cout << "\n\ns1 += s2 yields s1 = "; s1 += s2; // test overloaded concatenation cout << s1; // test cout << s1 += " cout << conversion constructor "\n\ns1 += \" to you\" yields\n"; to you"; // test conversion constructor "s1 = " << s1 << "\n\n"; 2003 Prentice Hall, Inc. All rights reserved. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 // test cout << << << // test cout << << << overloaded function call operator () for substring "The substring of s1 starting at\n" "location 0 for 14 characters, s1(0, 14), is:\n" s1( 0, 14 ) << "\n\n"; substring "to-end-of-String" option "The substring of s1 starting at\n" "location 15, s1(15, 0), is: " s1( 15, 0 ) << "\n\n"; // 0 is "to end of string" Outline fig08_09.cpp (3 of 4) 52 // test copy constructor String *s4Ptr = new String( s1 ); cout << "\n*s4Ptr = " << *s4Ptr << "\n\n"; // test assignment (=) operator with self-assignment cout << "assigning *s4Ptr to *s4Ptr\n"; *s4Ptr = *s4Ptr; // test overloaded assignment cout << "*s4Ptr = " << *s4Ptr << '\n'; // test destructor delete s4Ptr; 2003 Prentice Hall, Inc. All rights reserved. 74 75 76 77 78 79 80 81 82 83 84 85 86 // test s1[ 0 ] s1[ 6 ] cout << << using subscript operator to create lvalue = 'H'; = 'B'; "\ns1 after s1[0] = 'H' and s1[6] = 'B' is: " s1 << "\n\n"; Outline fig08_09.cpp (4 of 4) 53 // test subscript out of range cout << "Attempt to assign 'd' to s1[30] yields:" << endl; s1[ 30 ] = 'd'; // ERROR: subscript out of range return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. Conversion constructor: happy Conversion constructor: birthday Conversion constructor: s1 is "happy"; s2 is " birthday"; s3 is "" The results of comparing s2 and s1: s2 == s1 yields false s2 != s1 yields true s2 > s1 yields false s2 < s1 yields true s2 >= s1 yields false s2 <= s1 yields true Testing !s3: s3 is empty; assigning s1 to s3; operator= called s3 is "happy" s1 += s2 yields s1 = happy birthday s1 += " to you" yields Conversion constructor: to you Destructor: to you s1 = happy birthday to you Outline fig08_09.cpp (1 of 3) 54 The constructor and destructor are called for the temporary String (converted from the char * to you ). 2003 Prentice Hall, Inc. All rights reserved. Conversion constructor: happy birthday Copy constructor: happy birthday Destructor: happy birthday The substring of s1 starting at location 0 for 14 characters, s1(0, 14), is: happy birthday Destructor: happy birthday Conversion constructor: to you Copy constructor: to you Destructor: to you The substring of s1 starting at location 15, s1(15, 0), is: to you Destructor: to you Copy constructor: happy birthday to you *s4Ptr = happy birthday to you assigning *s4Ptr to *s4Ptr operator= called Attempted assignment of a String to itself *s4Ptr = happy birthday to you Destructor: happy birthday to you Outline fig08_09.cpp (2 of 3) 55 2003 Prentice Hall, Inc. All rights reserved. s1 after s1[0] = 'H' and s1[6] = 'B' is: Happy Birthday to you Attempt to assign 'd' to s1[30] yields: Error: Subscript 30 out of range Outline fig08_09.cpp (3 of 3) 56 2003 Prentice Hall, Inc. All rights reserved. 57 8.11 Overloading ++ and - Increment/decrement operators can be overloaded Add 1 to a Date object, d1 Prototype (member function) Date &operator++(); ++d1 same as d1.operator++() Prototype (non-member) Friend Date &operator++( Date &); ++d1 same as operator++( d1 ) 2003 Prentice Hall, Inc. All rights reserved. 58 8.11 Overloading ++ and - To distinguish pre/post increment Post increment has a dummy parameter int of 0 Prototype (member function) Date operator++( int ); d1++ same as d1.operator++( 0 ) friend Date operator++( Data &, int ); d1++ same as operator++( d1, 0 ) Prototype (non-member) Integer parameter does not have a name Not even in function definition 2003 Prentice Hall, Inc. All rights reserved. 59 8.11 Overloading ++ and - Return values Preincrement Returns by reference (Date &) lvalue (can be assigned) Postincrement Returns by value Returns temporary object with old value rvalue (cannot be on left side of assignment) Decrement operator analogous 2003 Prentice Hall, Inc. All rights reserved. 60 8.12 Case Study: A Date Class Example Date class Overloaded increment operator Change day, month and year Overloaded += operator Function to test for leap years Function to determine if day is last of month 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // Fig. 8.10: date1.h // Date class definition. #ifndef DATE1_H #define DATE1_H #include <iostream> using std::ostream; class Date { friend ostream &operator<<( ostream &, const Date & ); public: Date( int m = 1, int d = 1, int y = Note difference between pre 1900 ); // constructor void setDate( int, int, int ); // set the date and post increment. Date &operator++(); Date operator++( int ); // preincrement operator // postincrement operator Outline date1.h (1 of 2) 61 const Date &operator+=( int ); // add days, modify object bool leapYear( int ) const; bool endOfMonth( int ) const; // is this a leap year? // is this end of month? 2003 Prentice Hall, Inc. All rights reserved. 23 24 25 26 27 28 29 30 31 32 33 34 private: int month; int day; int year; static const int days[]; void helpIncrement(); }; // end class Date #endif // array of days per month // utility function Outline date1.h (2 of 2) 62 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Fig. 8.11: date1.cpp // Date class member function definitions. #include <iostream> #include "date1.h" // initialize static member at file scope; // one class-wide copy const int Date::days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Date constructor Date::Date( int m, int d, int y ) { setDate( m, d, y ); } // end Date constructor // set month, day and year void Date::setDate( int mm, int dd, int yy ) { month = ( mm >= 1 && mm <= 12 ) ? mm : 1; year = ( yy >= 1900 && yy <= 2100 ) ? yy : 1900; Outline date1.cpp (1 of 5) 63 2003 Prentice Hall, Inc. All rights reserved. 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // test for a if ( month == day = ( dd else day = ( dd leap year 2 && leapYear( year ) ) >= 1 && dd <= 29 ) ? dd : 1; >= 1 && dd <= days[ month ] ) ? dd : 1; Outline date1.cpp (2 of 5) 64 } // end function setDate // overloaded preincrement operator Date &Date::operator++() { helpIncrement(); return *this; // reference return to create an lvalue Postincrement updates object and returns a copy of the // overloaded postincrement operator; note that the dummy original. Do not return a // integer parameter does not have a parameter name reference to temp, because it Date Date::operator++( int ) is a local variable that will be { destroyed. Date temp = *this; // hold current state of object } // end function operator++ helpIncrement(); // return unincremented, saved, return temp; // value return; } // end function operator++ Also note that the integer temporary object parameter does not have a not a name. reference return 2003 Prentice Hall, Inc. All rights reserved. 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 // add specified number of days to date const Date &Date::operator+=( int additionalDays ) { for ( int i = 0; i < additionalDays; i++ ) helpIncrement(); return *this; // enables cascading Outline date1.cpp (3 of 5) 65 } // end function operator+= // if the year is a leap year, return true; // otherwise, return false bool Date::leapYear( int testYear ) const { if ( testYear % 400 == 0 || ( testYear % 100 != 0 && testYear % 4 == 0 ) ) return true; // a leap year else return false; // not a leap year } // end function leapYear 2003 Prentice Hall, Inc. All rights reserved. 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 // determine whether the day is the last day of the month bool Date::endOfMonth( int testDay ) const { if ( month == 2 && leapYear( year ) ) return testDay == 29; // last day of Feb. in leap year else return testDay == days[ month ]; } // end function endOfMonth // function to help increment the date void Date::helpIncrement() { // day is not end of month if ( !endOfMonth( day ) ) ++day; else // day is end of month and month < 12 if ( month < 12 ) { ++month; day = 1; } Outline date1.cpp (4 of 5) 66 2003 Prentice Hall, Inc. All rights reserved. 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 // last day of year else { ++year; month = 1; day = 1; } } // end function helpIncrement // overloaded output operator ostream &operator<<( ostream &output, const Date &d ) { static char *monthName[ 13 ] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; output << monthName[ d.month ] << ' ' << d.day << ", " << d.year; return output; // enables cascading Outline date1.cpp (5 of 5) 67 } // end function operator<< 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 8.12: fig08_12.cpp // Date class test program. #include <iostream> using std::cout; using std::endl; #include "date1.h" // Date class definition Outline fig08_12.cpp (1 of 2) 68 int main() { Date d1; // defaults to January 1, 1900 Date d2( 12, 27, 1992 ); Date d3( 0, 99, 8045 ); // invalid date cout << "d1 is " << d1 << "\nd2 is " << d2 << "\nd3 is " << d3; cout << "\n\nd2 += 7 is " << ( d2 += 7 ); d3.setDate( 2, 28, 1992 ); cout << "\n\n d3 is " << d3; cout << "\n++d3 is " << ++d3; Date d4( 7, 13, 2002 ); 2003 Prentice Hall, Inc. All rights reserved. 26 27 28 29 30 31 32 33 34 35 36 37 38 39 cout << << cout << cout << cout << << cout << cout << "\n\nTesting the preincrement operator:\n" " d4 is " << d4 << '\n'; "++d4 is " << ++d4 << '\n'; " d4 is " << d4; "\n\nTesting the postincrement operator:\n" " d4 is " << d4 << '\n'; "d4++ is " << d4++ << '\n'; " d4 is " << d4 << endl; Outline fig08_12.cpp (2 of 2) 69 return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. d1 is January 1, 1900 d2 is December 27, 1992 d3 is January 1, 1900 d2 += 7 is January 3, 1993 d3 is February 28, 1992 ++d3 is February 29, 1992 Testing d4 is ++d4 is d4 is Testing d4 is d4++ is d4 is the preincrement operator: July 13, 2002 July 14, 2002 July 14, 2002 the postincrement operator: July 14, 2002 July 14, 2002 July 15, 2002 Outline fig08_12.cpp output (1 of 1) 70 2003 Prentice Hall, Inc. All rights reserved. 8.13 Standard Library Classes string and vector Classes built into C++ Available for anyone to use string Similar to our String class 71 vector Dynamically resizable array Redo our String and Array examples Use string and vector 2003 Prentice Hall, Inc. All rights reserved. 8.13 Standard Library Classes string and vector Class string Header <string>, namespace std Can initialize string s1( hi ); Overloaded << cout << s1 72 Overloaded relational operators == != >= > <= < Assignment operator = Concatenation (overloaded +=) 2003 Prentice Hall, Inc. All rights reserved. 8.13 Standard Library Classes string and vector Class string Substring function substr s1.substr(0, 14); Starts at location 0, gets 14 characters S1.substr(15) Substring beginning at location 15 73 Overloaded [] Access one character No range checking (if subscript invalid) at function s1.at(10) Character at subscript 10 Has bounds checking Will end program if invalid (learn more in Chapter 13) 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 8.13: fig08_13.cpp // Standard library string class test program. #include <iostream> using std::cout; using std::endl; #include <string> using std::string; int main() { string s1( "happy" ); string s2( " birthday" ); string s3; // test cout << << << << << << << overloaded equality and relational operators "s1 is \"" << s1 << "\"; s2 is \"" << s2 "\"; s3 is \"" << s3 << '\"' "\n\nThe results of comparing s2 and s1:" "\ns2 == s1 yields " ( s2 == s1 ? "true" : "false" ) "\ns2 != s1 yields " ( s2 != s1 ? "true" : "false" ) Outline fig08_13.cpp (1 of 4) 74 2003 Prentice Hall, Inc. All rights reserved. 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 << << << << << << << << "\ns2 > s1 yields " ( s2 > s1 ? "true" : "false" ) "\ns2 < s1 yields " ( s2 < s1 ? "true" : "false" ) "\ns2 >= s1 yields " ( s2 >= s1 ? "true" : "false" ) "\ns2 <= s1 yields " ( s2 <= s1 ? "true" : "false" ); Outline fig08_13.cpp (2 of 4) 75 // test string member function empty cout << "\n\nTesting s3.empty():\n"; if ( s3.empty() ) { cout << "s3 is empty; assigning s1 to s3;\n"; s3 = s1; // assign s1 to s3 cout << "s3 is \"" << s3 << "\""; } // test overloaded string concatenation operator cout << "\n\ns1 += s2 yields s1 = "; s1 += s2; // test overloaded concatenation cout << s1; 2003 Prentice Hall, Inc. All rights reserved. 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 // test // with cout << s1 += " cout << // test cout << << << // test cout << << << overloaded string concatenation operator C-style string "\n\ns1 += \" to you\" yields\n"; to you"; "s1 = " << s1 << "\n\n"; string member function substr "The substring of s1 starting at location 0 for\n" "14 characters, s1.substr(0, 14), is:\n" s1.substr( 0, 14 ) << "\n\n"; substr "to-end-of-string" option "The substring of s1 starting at\n" "location 15, s1.substr(15), is:\n" s1.substr( 15 ) << '\n'; Outline fig08_13.cpp (3 of 4) 76 // test copy constructor string *s4Ptr = new string( s1 ); cout << "\n*s4Ptr = " << *s4Ptr << "\n\n"; // test assignment (=) operator with self-assignment cout << "assigning *s4Ptr to *s4Ptr\n"; *s4Ptr = *s4Ptr; cout << "*s4Ptr = " << *s4Ptr << '\n'; 2003 Prentice Hall, Inc. All rights reserved. 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 // test destructor delete s4Ptr; // test s1[ 0 ] s1[ 6 ] cout << << using subscript operator to create lvalue = 'H'; = 'B'; "\ns1 after s1[0] = 'H' and s1[6] = 'B' is: " s1 << "\n\n"; Outline fig08_13.cpp (4 of 4) 77 // test subscript out of range with string member function "at" cout << "Attempt to assign 'd' to s1.at( 30 ) yields:" << endl; s1.at( 30 ) = 'd'; // ERROR: subscript out of range return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. s1 is "happy"; s2 is " birthday"; s3 is "" The results of comparing s2 and s1: s2 == s1 yields false s2 != s1 yields true s2 > s1 yields false s2 < s1 yields true s2 >= s1 yields false s2 <= s1 yields true Testing s3.empty(): s3 is empty; assigning s1 to s3; s3 is "happy" s1 += s2 yields s1 = happy birthday s1 += " to you" yields s1 = happy birthday to you The substring of s1 starting at location 0 for 14 characters, s1.substr(0, 14), is: happy birthday Outline fig08_13.cpp output (1 of 2) 78 2003 Prentice Hall, Inc. All rights reserved. The substring of s1 starting at location 15, s1.substr(15), is: to you *s4Ptr = happy birthday to you assigning *s4Ptr to *s4Ptr *s4Ptr = happy birthday to you s1 after s1[0] = 'H' and s1[6] = 'B' is: Happy Birthday to you Attempt to assign 'd' to s1.at( 30 ) yields: abnormal program termination Outline fig08_13.cpp output (2 of 2) 79 2003 Prentice Hall, Inc. All rights reserved. 8.13 Standard Library Classes string and vector Class vector Header <vector>, namespace std Store any type vector< int > myArray(10) 80 Function size ( myArray.size() ) Overloaded [] Get specific element, myArray[3] Overloaded !=, ==, and = Inequality, equality, assignment 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 8.14: fig08_14.cpp // Demonstrating standard library class vector. #include <iostream> using std::cout; using std::cin; using std::endl; #include <iomanip> using std::setw; #include <vector> using std::vector; void outputVector( const vector< int > & ); void inputVector( vector< int > & ); int main() { vector< int > integers1( 7 ); vector< int > integers2( 10 ); Outline fig08_14.cpp (1 of 5) 81 // 7-element vector< int > // 10-element vector< int > 2003 Prentice Hall, Inc. All rights reserved. 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // print integers1 size and contents cout << "Size of vector integers1 is " << integers1.size() << "\nvector after initialization:\n"; outputVector( integers1 ); // print integers2 size and contents cout << "\nSize of vector integers2 is " << integers2.size() << "\nvector after initialization:\n"; outputVector( integers2 ); // input and print integers1 and integers2 cout << "\nInput 17 integers:\n"; inputVector( integers1 ); inputVector( integers2 ); cout << "\nAfter input, the vectors contain:\n" << "integers1:\n"; outputVector( integers1 ); cout << "integers2:\n"; outputVector( integers2 ); // use overloaded inequality (!=) operator cout << "\nEvaluating: integers1 != integers2\n"; Outline fig08_14.cpp (2 of 5) 82 2003 Prentice Hall, Inc. All rights reserved. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 if ( integers1 != integers2 ) cout << "integers1 and integers2 are not equal\n"; // create vector integers3 using integers1 as an // initializer; print size and contents vector< int > integers3( integers1 ); // copy constructor cout << "\nSize of vector integers3 is " << integers3.size() << "\nvector after initialization:\n"; outputVector( integers3 ); Outline fig08_14.cpp (3 of 5) 83 // use overloaded assignment (=) operator cout << "\nAssigning integers2 to integers1:\n"; integers1 = integers2; cout << "integers1:\n"; outputVector( integers1 ); cout << "integers2:\n"; outputVector( integers1 ); 2003 Prentice Hall, Inc. All rights reserved. 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 // use overloaded equality (==) operator cout << "\nEvaluating: integers1 == integers2\n"; if ( integers1 == integers2 ) cout << "integers1 and integers2 are equal\n"; // use overloaded subscript operator to create rvalue cout << "\nintegers1[5] is " << integers1[ 5 ]; // use overloaded subscript operator to create lvalue cout << "\n\nAssigning 1000 to integers1[5]\n"; integers1[ 5 ] = 1000; cout << "integers1:\n"; outputVector( integers1 ); // attempt to use out of range subscript cout << "\nAttempt to assign 1000 to integers1.at( 15 )" << endl; integers1.at( 15 ) = 1000; // ERROR: out of range return 0; } // end main Outline fig08_14.cpp (4 of 5) 84 2003 Prentice Hall, Inc. All rights reserved. 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 // output vector contents void outputVector( const vector< int > &array ) { for ( int i = 0; i < array.size(); i++ ) { cout << setw( 12 ) << array[ i ]; if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output cout << endl; } // end for if ( i % 4 != 0 ) cout << endl; } // end function outputVector // input vector contents void inputVector( vector< int > &array ) { for ( int i = 0; i < array.size(); i++ ) cin >> array[ i ]; } // end function inputVector Outline fig08_14.cpp (5 of 5) 85 2003 Prentice Hall, Inc. All rights reserved. Size of vector integers1 is 7 vector after initialization: 0 0 0 0 0 0 Size of vector integers2 is 10 vector after initialization: 0 0 0 0 0 0 0 0 Input 17 integers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 After input, the vectors contain: integers1: 1 2 3 5 6 7 integers2: 8 9 10 12 13 14 16 17 Evaluating: integers1 != integers2 integers1 and integers2 are not equal Outline 0 86 fig08_14.cpp output (1 of 2) 0 0 4 11 15 2003 Prentice Hall, Inc. All rights reserved. Size of vector integers3 is 7 vector after initialization: 1 2 3 5 6 7 Assigning integers2 to integers1: integers1: 8 9 10 12 13 14 16 17 integers2: 8 9 10 12 13 14 16 17 Evaluating: integers1 == integers2 integers1 and integers2 are equal integers1[5] is 13 Assigning 1000 to integers1[5] integers1: 8 9 10 12 1000 14 16 17 Attempt to assign 1000 to integers1.at( 15 ) abnormal program termination Outline 4 87 fig08_14.cpp output (2 of 2) 11 15 11 15 11 15 2003 Prentice Hall, Inc. All rights reserved.
Find millions of documents here - Study Guides, Homework Solutions, Papers, Exam Answer Keys and more. Course Hero has millions of course related materials that will enable you to learn better, faster and get an A in all your courses.
Below is a small sample set of documents:

Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived Classes 9.3 protected Members 9.4 Relationship between Base Classes and Derived Classes 9.5 Case Study: Three-Level Inheritance Hierarchy 9.6 C...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy 10.2.1 Invoking Base-Class Functions from DerivedClass Objects 10.2.2 Aiming Derived-Class Pointers at Base-Class Objects...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates 11.4 Class Templates 11.5 Class Templates and Nontype Parameters 11.6 Templates and Inheritance 11.7 Templates and Friends 11.8 Templates ...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 12 - C+ Stream Input/Output Outline 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3 Stream Output 12.3.1 Output of char * V...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 13 - Exception Handling Outline 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 13.11 13.12 13.13 Introduction Exception-Handling Overview Other Error-Handling Techniques Simple Exception-Handling Example: Divide by Zero Rethrowing an E...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 14 - File Processing Outline 14.1 Introduction 14.2 The Data Hierarchy 14.3 Files and Streams 14.4 Creating a Sequential-Access File 14.5 Reading Data from a Sequential-Access File 14.6 Updating Sequential-Access Files 14.7 Random-Access F...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Chapter 15 - Class string and String Stream Processing Outline 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 15.10 15.11 15.12 Introduction string Assignment and Concatenation Comparing strings Substrings Swapping strings string Characteristics Findin...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Chapter 16 - Web Programming with CGI Outline 16.1 16.2 16.3 16.4 16.5 16.6 16.7 16.8 16.9 16.10 16.11 16.12 16.13 16.14 16.15 16.16 16.17 Introduction HTTP Request Types Multi-Tier Architecture Accessing Web Servers Apache HTTP Server Requesting XHT...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 17 - Data Structures Outline 17.1 Introduction 17.2 Self-Referential Classes 17.3 Dynamic Memory Allocation and Data Structures 17.4 Linked Lists 17.5 Stacks 17.6 Queues 17.7 Trees 2003 Prentice Hall, Inc. All rights reserved. 2 17.1 ...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Chapter 18 - Bits, Characters, Strings and Structures Outline 18.1 Introduction 18.2 StructureDefinitions 18.3 InitializingStructures 18.4 UsingStructureswithFunctions 18.5 typedef 18.6 Example:HighPerformanceCardShufflingandDealing Simulation 18.7 B...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 19 - The Preprocessor Outline 19.1 Introduction 19.2 The #include Preprocessor Directive 19.3 The #define Preprocessor Directive: Symbolic Constants 19.4 The #define Preprocessor Directive: Macros 19.5 Conditional Compilation 19.6 The #err...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 20 - C Legacy Code Topics Outline 20.1 Introduction 20.2 Redirecting Input/Output on UNIX and DOS Systems 20.3 Variable-Length Argument Lists 20.4 Using Command-Line Arguments 20.5 Notes on Compiling Multiple-Source-File Programs 20.6 Prog...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
Chapter 21 - Standard Template Library (STL) Outline 21.1 Introduction to the Standard Template Library (STL) 21.1.1 Introduction to Containers 21.1.2 Introduction to Iterators 21.1.3 Introduction to Algorithms 21.2 Sequence Containers 21.2.1 vector ...
Izmir University of Economics >> BILGISAYAR >> cs116 (Spring, 2009)
1 Chapter 22 - Other Topics Outline 22.1 Introduction 22.2 const_cast Operator 22.3 reinterpret_cast Operator 22.4 namespaces 22.5 Operator Keywords 22.6 explicit Constructors 22.7 mutable Class Members 22.8 Pointers to Class Members (.* and ->*) 22...
Saint Louis >> IB >> 511 (Spring, 2009)
Solutions Manual Fundamentals of Corporate Finance 8th edition Ross, Westerfield, and Jordan Updated 03-05-2007 CHAPTER 1 INTRODUCTION TO CORPORATE FINANCE Answers to Concepts Review and Critical Thinking Questions 1. Capital budgeting (deciding whe...
SUNY Brockport >> HST >> HST 102.07 (Fall, 2007)
Mike Gemmati HST 102.07 Dr. Malik November 4th, 2007 Critical Views of September 11th: Analyses from Around the World Critical Views of September 11: Analyses from Around the World provides a wide-ranging collection of views interpreting trends in in...
SUNY Brockport >> CIS >> Cis 106 (Spring, 2009)
Mike Gemmati Mr. Bossert CIS 106.02 November 25th 2007 Computer Ethics As of September 2003, there were approximately 70 million Americans or about 62 percent of the American population had at least one home computer. Another statistic is that about ...
SUNY Brockport >> HST >> 102.07 (Spring, 2009)
Mike Gemmati HST 102.07 Modern World Dr. Malik October 6, 2007 Question # 4 A revolution by definition is a drastic and far-reaching change in ways of thinking and behaving. Variously defined revolutions have been happening throughout human history. ...
SUNY Brockport >> HST >> 102.07 (Spring, 2009)
Mike Gemmati Modern World 102 Dr. Malik Final Exam December 7th 2007 Question 1 In an ever changing society, one based on technology, religion, the economy, and many other factors, it is now more then ever important for people to have an open mind. A...
SUNY Brockport >> HST >> 102.07 (Spring, 2009)
Mike Gemmati Dr. Malik HST 102 12/08/07 Question # 3 World War One or \'The Great War\' as it became known occurred due to many causes, some of which still remain unexposed today. The obvious trigger for the war was the assassination of the heir to the...
SUNY Brockport >> HST >> 102.07 (Spring, 2009)
Mike Gemmati Dr. Malik HST 102.07 10/7/07 Question # 1 Martin Luther King Jr., a famous American civil rights leader once said, Nothing in the world is more dangerous than a sincere ignorance and conscientious stupidity. When deciding my view point o...
SUNY Brockport >> HST >> 102.07 (Spring, 2009)
Taoism The Old Master was Lao Tzu and was born in 604 b.c. The three meanings of Tao (path) 1) The way of the ultimate reality to vast for human rationality to fathom 2) The way of the universe the norm, the rhythm, the driving power in all nature...
SUNY Brockport >> ACC >> 182 (Spring, 2008)
Description Sales Percentage Sales Variable Cost of Package Sales Commison Royalties Variable Promotional and Selling Costs Fixed Costs Totals Scratch January 4% $6.00 $3.00 7% 12% 6% $150,000 February 5% $480,000 $600,000 $240,000 $300,000 $33,600 ...
SUNY Brockport >> BUS >> 375 (Fall, 2008)
Part One: Foundations of American Law 1. The Nature of Law 2 Types and Classifications of Law 2 The Types of Law 2 Priority Rules 7 Classifications of Law 8 Jurisprudence 8 Legal Provision 8 Natural Law 8 American Legal Realism 10 Sociologic...
SUNY Brockport >> BUS >> 375 (Fall, 2008)
Mike Gemmati Prof. VanGraafeiland 10/30/08 BUS 375 On October 29th I went to the New York State Supreme Court seventh judicial district located in the Hall of Justice in downtown Rochester. I arrived at the court house around 2:15 just as the trial w...
SUNY Brockport >> BUS >> 375 (Fall, 2008)
CHAPTER 1 THE NATURE OF LAW 1. One of the functions of constitutions is to prohibit certain government action. T 2. Administrative agencies promulgate administrative regulations and agency decisions, which have the force of law within that agency. T ...
SUNY Brockport >> MTH >> MTH (Fall, 2008)
Chapter 1 Types of Data: Quantitative (numbers), Qualitative (Categorical in nature) Data Collection Methods: 1. Observational 2. Published source 3. Survey 4. Designed Experiment Problems With nonrandom samples: 1. Selection Bias 2. Nonresponse Bias...
SUNY Brockport >> MTH >> MTH (Fall, 2008)
School U of Virginia William & Mary U of Michigan, Ann Arbor U.C.L.A. U of California, Berkeley SUNY, Delhi U of California, San Diego Penn State, University Park U of North Carolina College of New Jersey U of California, Davis SUNY, Geneseo Miami U....
SUNY Brockport >> MTH >> MTH (Fall, 2008)
List Price 89900 96500 70000 79900 94900 84900 99000 124900 128000 104900 Sale Price 75000 90500 68000 73500 92400 84000 99000 123000 123000 109900 DOM (days on market) 76 48 42 9 27 140 10 75 24 4 # Rooms 5 7 5 5 6 6 6 8 7 6 # Bedrooms 3 4 2 3 2...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
Abstract idea: hEarTbReaKer o8x (11:52:00 PM): i think ur thesis should be something along the lines of terrorism\'s effects on international tourism can be both awful and wonderful. and then u talk about those bad things u just mentioned to me. then ...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
Maldives By: Mike Gemmati History The Maldives was long a sultanate, first under Dutch and then under British protection. It became a republic in 1968, three years after independence. Following riots in the capital Male in August 2004, the president...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
[Type text] [Type text] [Type text] References Abraham Pizam and Yoel Mansfield (1996). Tourism, Crime and International Security. New York: John Wiley & Sons, p. 175. Anson, C. (1999, August). Planning for Peace: The Role of Tourism in the Afterm...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
Sources for paper: 1) International Terrorism in Latin America: Effects on Foreign Investment and Tourism Terrorist attacks have economic consequences. Some of the consequences are largely unintended, as happens when money is diverted to police force...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
Terrorism and Tourism 1 The Effects of Terrorism and Crime on International Tourism Mike Gemmati International Tourism 315 Section 01 Professor Hardy October 16, 2006 Terrorism and Tourism Abstract 2 The international tourism industry which brin...
SUNY Brockport >> REL >> REL 315 (Spring, 2009)
Mike Gemmati Rick Hardy REL 315 01 October 2008 Top 10 Caribbean Resorts After watching the Worlds Best documentary on the Travel channel I now have a better idea of the best resorts in the Caribbean. This one hour show counted down the top 10 hotels...
#3
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
MikeGemmati ACC28103 HW#3 (a) FIFO Beginning inventory Oct 1 Purchases Units Unit Cost 400 $10.00 8-Oct 16-Oct 24-Oct 800 600 200 200 100 $10.40 $10.80 $11.60 $11.60 $10.80 Cost of goods available for sale (2,000 units) Less: Ending inventory Cost...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Mike Gemmati Table 1: Bus #1 (change title for Bus #3 table) Depreciatio Accumulate n Expense d Cost: Net Book Value per Table Depreciatio at Year-end 2: n at YearFiscal Year Bus #1 end 2005 $86,000 $20,000 $20,000 $66,000 2006 $66,000 $20,000 $40,0...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Mike Gemmati Acc 281-03 3/31/08 Part E The method that produced the highest gross profit was the FIFO method. This is largely because by using the First in First Out method in a time of rising prices your cost of goods sold is lower therefore increa...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Name: Exercise: Course: Date: (a.) Date 4/1/07 Mike Gemmati HOMEWORK ASSIGNMENT #2 ACCOUNTING 281-01 22-Feb-08 General Ledger Account Titles and Explanation Cash Common Stock To issue shares of stock for cash No Entry Rent Expense Cash Paid office r...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Part A Charlie Company Income Statement For the Year Ended December 31, 2007 Revenues Sales Revenue Expenses cost of goods sold Salaries Expense Depreciation Expense Interest Expense Total Expenses Net Income $36,500 13,000 $5,200 4,800 2,000 25,000...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Name: Exercise: Course: Date: (a.) Date 4/1/07 Mike Gemmati HOMEWORK ASSIGNMENT #2 ACCOUNTING 281-01 22-Feb-08 General Ledger Account Titles and Explanation Cash Common Stock To issue shares of stock for cash No Entry Rent Expense Cash Paid office r...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Mike Gemmati ACC 281-01 P. Brown 4/21/2008 Question 2(all numbers reported in thousands) A) The total cost and book value of property, plant and equipment at December 31, 2004 was $178,750. B) Tootsie Roll Industries, Inc. uses a straight line metho...
SUNY Brockport >> ACC >> ACC 281 (Spring, 2009)
Name: Exercise: Course: Date: (a.) Date 4/1/07 Mike Gemmati HOMEWORK ASSIGNMENT #2 ACCOUNTING 281-01 22-Feb-08 General Ledger Account Titles and Explanation Cash Common Stock To issue shares of stock for cash No Entry Rent Expense Cash Paid office r...
SUNY Brockport >> BUS >> Bus 333 (Spring, 2009)
Case D-7 Callaway Golf: The Global Challenge Executive Summary Callaway Golf was founded in 1982 when Ely R. Callaway invested $400,000 in a company called Hickory Stick. The company originally named Callaway Hickory, later renamed to Callaway Golf. ...
SUNY Brockport >> BUS >> Bus 333 (Spring, 2009)
1.) What are the pros and cons of a global versus a multi-domestic approach to marketing golf clubs for Callaway? Which approach do you feel would have more merit and why? A firms orientation toward and strategy for global markets and marketing defin...
University of Mississippi Medical Center >> PSYCH >> 1000 (Fall, 2008)
Psychology: 8/27/08 Definition of Psychology: The scientific study of behavior and mental processes -Three Important Parts of Definition a. Behavior: Actions, things we do -Overt behavior b. Mental Processes: (Tough because they cannot be seen) -Thou...
University of Mississippi Medical Center >> PSYCH >> 1000 (Spring, 2009)
8/29/08 Psychological Theory -An idea, an explantion (broad) -Connect two big ideas -Examples: Frustraion-Aggression Theory, Similarity-Attraction Theory What is a Hypothesis? A prediction, stemming from a thory, stated in a way that allows it to be ...
University of Mississippi Medical Center >> PSYCH >> 1000 (Spring, 2009)
Review Questions for Ch 1 1. How old is the field of psychology? William Wundt found it in December of 1879 2. What is the definition of psychology? Psychology is the scientific study of behavior and mental porcess 3. What is included in this definit...
UCSB >> PHYS >> Phys4 (Spring, 2009)
LHC ...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
!1 !2 n1 sin(!1) = n2 sin(!2) n2 sin(!3) = n1 sin(!4) !3 !4 !1 !2 n1 sin(!1) = n2 sin(!2) but n2 is \" dependent n2(blue) > n2(red) so blue bends more So is this splitting of red and blue what causes a rainbow? Yes, sort of. Note that red is o...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PHYS >> Phys4 (Spring, 2009)
...
UCSB >> PSYCH >> 1 (Spring, 2009)
Development Nature-Nurture Problem Is a trait due to heredity or to the environment? Sometimes, the problem is stated as maturation vs. enculturation. Environment can be: chemical pathogen psychological pre-, peri-, or post-natal Nature-Nur...
UCSB >> PSYCH >> 1 (Spring, 2009)
Evolution and Behavior Sir Charles Darwin 1809-1882 Info About Darwin Darwins Main Contributions to Psychology Continuity of life forms Mental evolution Sexology Voyage Aboard H. M. S. Beagle 1831-1836 Info About Darwins The Voyage of the B...
What are you waiting for?