Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a...

46
11 Operator Overloading; String and Array Objects OBJECTIVES In this chapter you will learn: To redefine (overload) operators to work with new abstract data types (ADTs). To convert objects from one class to another class. When to, and when not to, overload operators. To create Array , String and Date classes that demonstrate operator overloading. To use overloaded operators and other member functions of standard library class string. To use keyword explicit to prevent the compiler from using single-argument constructors to perform implicit conversions. The whole difference between construction and creation is exactly this: that a thing constructed can only be loved after it is constructed; but a thing created is loved before it exists. —Gilbert Keith Chesterton The die is cast. —Julius Caesar Our doctor would never really operate unless it was necessary. He was just that way. If he didn’t need the money, he wouldn’t lay a hand on you. —Herb Shriner

Transcript of Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a...

Page 1: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

11Operator Overloading; String and Array Objects

O B J E C T I V E SIn this chapter you will learn:

■ To redefine (overload) operators to work with new abstract data types (ADTs).

■ To convert objects from one class to another class.

■ When to, and when not to, overload operators.

■ To create Array, String and Date classes that demonstrate operator overloading.

■ To use overloaded operators and other member functions of standard library class string.

■ To use keyword explicit to prevent the compiler from using single-argument constructors to perform implicit conversions.

The whole difference between construction and creation is exactly this: that a thing constructed can only be loved after it is constructed; but a thing created is loved before it exists.—Gilbert Keith Chesterton

The die is cast.—Julius Caesar

Our doctor would never really operate unless it was necessary. He was just that way. If he didn’t need the money, he wouldn’t lay a hand on you.—Herb Shriner

cpphtp5_11_IM.fm Page 571 Thursday, December 23, 2004 4:15 PM

Page 2: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

572 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

Self-Review Exercises11.1 Fill in the blanks in each of the following:

a) Suppose a and b are integer variables and we form the sum a + b. Now suppose c andd are floating-point variables and we form the sum c + d. The two + operators here areclearly being used for different purposes. This is an example of .

ANS: operator overloading.b) Keyword introduces an overloaded-operator function definition.ANS: operator.c) To use operators on class objects, they must be overloaded, with the exception of oper-

ators , and .ANS: assignment (=), address (&), comma (,).d) The , and of an operator cannot be changed by

overloading the operator.ANS: precedence, associativity, “arity.”

11.2 Explain the multiple meanings of the operators << and >> in C++.ANS: Operator >> is both the right-shift operator and the stream extraction operator,

depending on its context. Operator << is both the left-shift operator and the streaminsertion operator, depending on its context.

11.3 In what context might the name operator/ be used in C++?ANS: For operator overloading: It would be the name of a function that would provide an

overloaded version of the / operator for a specific class.

11.4 (True/False) In C++, only existing operators can be overloaded.ANS: True.

11.5 How does the precedence of an overloaded operator in C++ compare with the precedenceof the original operator?

ANS: The precedence is identical.

Solutions11.6 Give as many examples as you can of operator overloading implicit in C++. Give a reason-able example of a situation in which you might want to overload an operator explicitly in C++.

ANS: In C, the operators +, -, *, and & are overloaded. The context of these operators de-termines how they are used. It can be argued that the arithmetic operators are all over-loaded, because they can be used to perform operations on more than one type ofdata. In C++, the same operators as in C are overloaded, as well as << and >>. Onesituation in which you might want to overload an operator would be in the sortingof objects. In [*** Chapter 7 ***] you were introduced to sorting, where the equalityand relational operators were used to determine when a value was greater than, equalto or less than another value. These operators can be overloaded to compare (andsort) objects—for instance, sorting GradeBook objects alphabetically by course name.

11.7 The operators that cannot be overloaded are , , and.

ANS: ., ?:, .*, and ::.

11.8 String concatenation requires two operands—the two strings that are to be concatenated.In the text, we showed how to implement an overloaded concatenation operator that concatenatesthe second String object to the right of the first String object, thus modifying the first String ob-ject. In some applications, it is desirable to produce a concatenated String object without modifyingthe String arguments. Implement operator+ to allow operations such as

cpphtp5_11_IM.fm Page 572 Thursday, December 23, 2004 4:15 PM

Page 3: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 573

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

string1 = string2 + string3;

1 // Exercise 11.8 Solution: String.h2 // Header file for class String.3 #ifndef STRING_H4 #define STRING_H56 #include <cstring> 7 #include <cassert>89 class String

10 {11 friend ostream &operator<<( ostream &output, const String &s );12 public:13 String( const char * const = "" ); // conversion constructor14 String( const String & ); // copy constructor15 ~String(); // destructor16 const String &operator=( const String & );17 String operator+( const String & );18 private:19 char *sPtr; // pointer to start of string20 int length; // string length21 }; // end class String2223 #endif

1 // Exercise 11.8 Solution: String.cpp2 // Member-function definitions for String.cpp3 #include <iostream> 4 using std::cout; 5 using std::ostream;67 #include <cstring> // strcpy and strcat prototypes 8 #include "String.h" // String class definition9

10 // conversion constructor: convert a char * to String11 String::String( const char * const zPtr )12 {13 length = strlen( zPtr ); // compute length14 sPtr = new char[ length + 1 ]; // allocate storage15 assert( sPtr != 0 ); // terminate if memory not allocated16 strcpy( sPtr, zPtr ); // copy literal to object17 } // end String conversion constructor1819 // copy constructor20 String::String( const String &copy )21 {22 length = copy.length; // copy length23 sPtr = new char[ length + 1 ]; // allocate storage24 assert( sPtr != 0 ); // ensure memory allocated25 strcpy( sPtr, copy.sPtr ); // copy string

cpphtp5_11_IM.fm Page 573 Thursday, December 23, 2004 4:15 PM

Page 4: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

574 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

26 } // end String copy constructor2728 // destructor29 String::~String()30 {31 delete [] sPtr; // reclaim string32 } // end destructor3334 // overloaded = operator; avoids self assignment35 const String &String::operator=( const String &right )36 {37 if ( &right != this ) // avoid self assignment38 {39 delete [] sPtr; // prevents memory leak40 length = right.length; // new String length41 sPtr = new char[ length + 1 ]; // allocate memory42 assert( sPtr != 0 ); // ensure memory allocated43 strcpy( sPtr, right.sPtr ); // copy string44 }45 else46 cout << "Attempted assignment of a String to itself\n";4748 return *this; // enables concatenated assignments49 } // end function operator=5051 // concatenate right operand and this object and store in temp object52 String String::operator+( const String &right )53 {54 String temp;5556 temp.length = length + right.length;57 temp.sPtr = new char[ temp.length + 1 ]; // create space58 assert( sPtr != 0 ); // terminate if memory not allocated59 strcpy( temp.sPtr, sPtr ); // left part of new String60 strcat( temp.sPtr, right.sPtr ); // right part of new String61 return temp; // enables concatenated calls62 } // end function operator+6364 // overloaded output operator65 ostream & operator<<( ostream &output, const String &s )66 {67 output << s.sPtr;68 return output; // enables concatenation69 } // end function operator<<

1 // Exercise 11.8 Solution: ex11_08.cpp2 // Demonstrating overloaded + operator that does not modify operands3 #include <iostream> 4 using std::cout; 5 using std::endl; 67 #include "String.h" 89 int main()

cpphtp5_11_IM.fm Page 574 Thursday, December 23, 2004 4:15 PM

Page 5: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 575

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.9 (Ultimate operator overloading exercise) To appreciate the care that should go into selectingoperators for overloading, list each of C++’s overloadable operators, and for each, list a possiblemeaning (or several, if appropriate) for each of several classes you have studied in this text. We sug-gest you try:

a) Arrayb) Stackc) String

After doing this, comment on which operators seem to have meaning for a wide variety of classes.Which operators seem to be of little value for overloading? Which operators seem ambiguous?

11.10 Now work the process described in Exercise 11.9 in reverse. List each of C++’s overloadableoperators. For each, list what you feel is perhaps the “ultimate operation” the operator should beused to represent. If there are several excellent operations, list them all.

11.11 One nice example of overloading the function call operator () is to allow another form ofdouble-array subscripting popular in some programming languages. Instead of saying

chessBoard[ row ][ column ]

for an array of objects, overload the function call operator to allow the alternate form

chessBoard( row, column )

Create a class DoubleSubscriptedArray that has similar features to class Array in Figs. 11.6–11.7. At construction time, the class should be able to create an array of any number of rows and anynumber of columns. The class should supply operator() to perform double-subscripting operations.For example, in a 3-by-5 DoubleSubscriptedArray called a, the user could write a( 1, 3 ) to accessthe element at row 1 and column 3. Remember that operator() can receive any number of argu-ments (see class String in Figs. 11.9–11.10 for an example of operator()). The underlying represen-tation of the double-subscripted array should be a single-subscripted array of integers with rows *columns number of elements. Function operator() should perform the proper pointer arithmetic toaccess each element of the array. There should be two versions of operator()—one that returns int &(so that an element of a DoubleSubscriptedArray can be used as an lvalue) and one that returnsconst int & (so that an element of a const DoubleSubscriptedArray can be used only as an rvalue).

10 {11 String string1, string2( "The date is" );12 String string3( " August 1, 1993" );1314 // test overloaded operators15 cout << "string1 = string2 + string3\n";16 string1 = string2 + string3; // tests overloaded = and + operator 17 cout << "\"" << string1 << "\" = \"" << string2 << "\" + \""18 << string3 << "\"" << endl;19 return 0;20 } // end main

string1 = string2 + string3"The date is August 1, 1993" = "The date is" + " August 1, 1993"

cpphtp5_11_IM.fm Page 575 Thursday, December 23, 2004 4:15 PM

Page 6: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

576 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

The class should also provide the following operators: ==, !=, =, << (for outputting the array in rowand column format) and >> (for inputting the entire array contents).

1 // Exercise 11.11 Solution: DoubleSubscriptedArray.h2 // DoubleSubscriptedArray class for storing3 // double subscripted arrays of integers.4 #ifndef DOUBLE_SUBSCRIPTED_ARRAY_H5 #define DOUBLE_SUBSCRIPTED_ARRAY_H67 #include <iostream>8 using std::ostream;9 using std::istream;

1011 class DoubleSubscriptedArray12 {13 friend ostream &operator<<(14 ostream &, const DoubleSubscriptedArray & );15 friend istream &operator>>( istream &, DoubleSubscriptedArray & );16 public:17 DoubleSubscriptedArray( int = 3, int = 3 ); // default constructor1819 // copy constructor20 DoubleSubscriptedArray( const DoubleSubscriptedArray & );2122 ~DoubleSubscriptedArray(); // destructor23 int getRowSize() const; // return number of rows24 int getColumnSize() const; // return number of columns2526 const DoubleSubscriptedArray &operator=(27 const DoubleSubscriptedArray & ); // assignment operator2829 // equality operator30 bool operator==( const DoubleSubscriptedArray & ) const;3132 // inequality operator; returns opposite of == operator33 bool operator!=( const DoubleSubscriptedArray &right ) const34 {35 // invokes DoubleSubscriptedArray::operator==36 return !( *this == right );37 } // end function operator!=3839 // function call operator for non-const objects40 // returns modifiable lvalue41 int &operator()( int, int );4243 // function call operator for const objects returns rvalue44 int operator()( int, int ) const;45 private:46 int rowSize; // number of rows in array47 int columnSize; // number of columns in array48 int *ptr; // pointer to first element of pointer-based array49 }; // end class DoubleSubscriptedArray5051 #endif

cpphtp5_11_IM.fm Page 576 Thursday, December 23, 2004 4:15 PM

Page 7: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 577

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

1 // Exercise 11.11 Solution: DoubleSubscriptedArray.cpp2 // Member-function definitions for class DoubleSubscriptedArray.3 #include <iostream>4 using std::cerr;5 using std::cout;6 using std::cin;7 using std::endl;89 #include <iomanip>

10 using std::setw;1112 #include <cstdlib> // exit function prototype13 using std::exit;1415 // DoubleSubscriptedArray class definition16 #include "DoubleSubscriptedArray.h"1718 // default constructor for class DoubleSubscriptedArray19 DoubleSubscriptedArray::DoubleSubscriptedArray(20 int rowSizeEntered, int columnSizeEntered )21 {22 // validate row and column size23 rowSize = ( rowSizeEntered > 0 ? rowSizeEntered : 3 );24 columnSize = ( columnSizeEntered > 0 ? columnSizeEntered : 3 );2526 ptr = new int[ rowSize * columnSize ]; // create space for array2728 for ( int loop = 0; loop < rowSize * columnSize; loop++ )29 ptr[ loop ] = 0; // set pointer-based array element30 } // end DoubleSubscriptedArray default constructor3132 // copy constructor for class DoubleSubscriptedArray;33 // must receive a reference to prevent infinite recursion34 DoubleSubscriptedArray::DoubleSubscriptedArray(35 const DoubleSubscriptedArray &arrayToCopy )36 : rowSize( arrayToCopy.rowSize ), columnSize( arrayToCopy.columnSize )37 {38 ptr = new int[ rowSize * columnSize ]; // create space for array3940 for ( int loop = 0; loop < rowSize * columnSize; loop++ )41 ptr[ loop ] = arrayToCopy.ptr[ loop ]; // copy into object42 } // end DoubleSubscriptedArray copy constructor4344 // destructor for class DoubleSubscriptedArray45 DoubleSubscriptedArray::~DoubleSubscriptedArray()46 {47 delete [] ptr; // release pointer-based array space48 } // end destructor4950 // return number of rows of DoubleSubscriptedArray51 int DoubleSubscriptedArray::getRowSize() const52 {53 return rowSize; // number of rows in DoubleSubscriptedArray

cpphtp5_11_IM.fm Page 577 Thursday, December 23, 2004 4:15 PM

Page 8: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

578 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

54 } // end function getRowSize5556 // return number of columns of DoubleSubscriptedArray57 int DoubleSubscriptedArray::getColumnSize() const58 {59 return columnSize; // number of columns in DoubleSubscriptedArray60 } // end function getColumnSize6162 // overloaded assignment operator;63 // const return avoids: ( a1 = a2 ) = a364 const DoubleSubscriptedArray &DoubleSubscriptedArray::operator=(65 const DoubleSubscriptedArray &right )66 {67 if ( &right != this ) // avoid self-assignment68 {69 // for arrays of different sizes, deallocate original70 // left-side array, then allocate new left-side array71 if ( rowSize * columnSize != right.rowSize * right.columnSize )72 {73 delete [] ptr; // release space74 rowSize = right.rowSize; // resize this object75 columnSize = right.columnSize;76 ptr = new int[ rowSize * columnSize ]; // create space for copy77 } // end inner if7879 for ( int loop = 0; loop < rowSize * columnSize; loop++ )80 ptr[ loop ] = right.ptr[ loop ]; // copy into object81 } // end outer if8283 return *this; // enables x = y = z, for example84 } // end function operator=8586 // determine if two DoubleSubscriptedArrays are equal and87 // return true, otherwise return false88 bool DoubleSubscriptedArray::operator==(89 const DoubleSubscriptedArray &right ) const90 {91 if ( rowSize * columnSize != right.rowSize * right.columnSize )92 return false; // arrays of different number of elements9394 for ( int loop = 0; loop < rowSize * columnSize; loop++ )95 if ( ptr[ loop ] != right.ptr[ loop ] )96 return false; // DoubleSubscriptedArray contents are not equal9798 return true; // DoubleSubscriptedArrays are equal99 } // end function operator==100101 // overloaded subscript operator for non-const DoubleSubscriptedArrays;102 // reference return creates a modifiable lvalue103 int &DoubleSubscriptedArray::operator()(104 int rowSubscript, int columnSubscript )105 {106 // check for subscript out-of-range error107 if ( ( rowSubscript < 0 || rowSubscript >= rowSize ) ||108 ( columnSubscript < 0 || columnSubscript >= columnSize ) )

cpphtp5_11_IM.fm Page 578 Thursday, December 23, 2004 4:15 PM

Page 9: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 579

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

109 {110 cerr << "\nError: One or both subscripts out of range" << endl;111 exit( 1 ); // terminate program; one or both subscripts out of range112 } // end if113114 // reference return115 return ptr[ ( rowSubscript * columnSize ) + columnSubscript ];116 } // end function operator()117118 // overloaded subscript operator for const DoubleSubscriptedArrays119 // const reference return creates an rvalue120 int DoubleSubscriptedArray::operator()(121 int rowSubscript, int columnSubscript ) const122 {123 // check for subscript out-of-range error124 if ( ( rowSubscript < 0 || rowSubscript >= rowSize ) ||125 ( columnSubscript < 0 || columnSubscript >= columnSize ) )126 {127 cerr << "\nError: One or both subscripts out of range" << endl;128 exit( 1 ); // terminate program; one or both subscripts out of range129 } // end if130131 // returns copy of this element132 return ptr[ ( rowSubscript * columnSize ) + columnSubscript ];133 } // end function operator()134135 // overloaded input operator for class DoubleSubscriptedArray;136 // inputs values for entire DoubleSubscriptedArray137 istream &operator>>( istream &input, DoubleSubscriptedArray &a )138 {139 for ( int loop = 0; loop < a.rowSize * a.columnSize; loop++ )140 input >> a.ptr[ loop ];141142 return input; // enables cin >> x >> y;143 } // end function operator>>144145 // overloaded output operator for class DoubleSubscriptedArray146 ostream &operator<<( ostream &output, const DoubleSubscriptedArray &a )147 {148 for ( int loop = 0; loop < a.rowSize; loop++ )149 {150 for ( int loop2 = 0; loop2 < a.columnSize; loop2++ )151 output << a.ptr[ ( loop * a.columnSize ) + loop2 ] << ' ';152153 output << endl;154 } // end for155156 return output; // enables cout << x << y;157 } // end function operator<<

1 // Exercise 11.11 Solution: ex11_11.cpp2 // DoubleSubscriptedArray class test program.

cpphtp5_11_IM.fm Page 579 Thursday, December 23, 2004 4:15 PM

Page 10: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

580 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

3 #include <iostream>4 using std::cout;5 using std::cin;6 using std::endl;78 #include "DoubleSubscriptedArray.h"9

10 int main()11 {12 DoubleSubscriptedArray integers1( 2, 4 ); // seven-element array13 DoubleSubscriptedArray integers2; // 3-by-3 array by default1415 // print integers1 size and contents16 cout << "Size of DoubleSubscriptedArray integers1 is "17 << integers1.getRowSize() << " X " << integers1.getColumnSize()18 << "\nDoubleSubscriptedArray after initialization:\n" << integers1;1920 // print integers2 size and contents21 cout << "\nSize of DoubleSubscriptedArray integers2 is "22 << integers2.getRowSize() << " X " << integers2.getColumnSize()23 << "\nDoubleSubscriptedArray after initialization:\n" << integers2;2425 // input and print integers1 and integers226 cout << "\nEnter 17 integers:" << endl;27 cin >> integers1 >> integers2;2829 cout << "\nAfter input, the DoubleSubscriptedArrays contain:\n"30 << "integers1:\n" << integers131 << "\nintegers2:\n" << integers2 << endl;3233 // use overloaded inequality (!=) operator34 cout << "Evaluating: integers1 != integers2" << endl;3536 if ( integers1 != integers2 )37 cout << "integers1 and integers2 are not equal" << endl;3839 // create DoubleSubscriptedArray integers3 using integers1 as an40 // initializer with copy constructor; print size and contents41 DoubleSubscriptedArray integers3( integers1 );4243 cout << "\nSize of DoubleSubscriptedArray integers3 is "44 << integers3.getRowSize() << " X " << integers3.getColumnSize()45 << "\nDoubleSubscriptedArray after initialization:\n" << integers3;4647 // use overloaded assignment (=) operator48 cout << "\nAssigning integers2 to integers1:" << endl;49 integers1 = integers2; // note target Array is smaller5051 cout << "integers1:\n" << integers152 << "\nintegers2:\n" << integers2;5354 // use overloaded equality (==) operator55 cout << "\nEvaluating: integers1 == integers2" << endl;5657 if ( integers1 == integers2 )

cpphtp5_11_IM.fm Page 580 Thursday, December 23, 2004 4:15 PM

Page 11: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 581

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

58 cout << "integers1 and integers2 are equal" << endl;5960 // use overloaded subscript operator to create rvalue61 cout << "\nintegers1( 1, 2 ) is " << integers1( 1, 2 );6263 // use overloaded subscript operator to create lvalue64 cout << "\n\nAssigning 1000 to integers1( 1, 2 )" << endl;65 integers1( 1, 2 ) = 1000;66 cout << "integers1:\n" << integers1;6768 // attempt to use out-of-range subscript69 cout << "\nAttempt to assign 1000 to integers1( 15, 2 )" << endl;70 integers1( 15, 2 ) = 1000; // ERROR: out of range71 return 0;72 } // end main

cpphtp5_11_IM.fm Page 581 Thursday, December 23, 2004 4:15 PM

Page 12: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

582 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

Size of DoubleSubscriptedArray integers1 is 2 X 4DoubleSubscriptedArray after initialization:0 0 0 0 0 0 0 0

Size of DoubleSubscriptedArray integers2 is 3 X 3DoubleSubscriptedArray after initialization:0 0 0 0 0 0 0 0 0

Enter 17 integers:10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

After input, the DoubleSubscriptedArrays contain:integers1:10 11 12 13 14 15 16 17

integers2:18 19 20 21 22 23 24 25 26

Evaluating: integers1 != integers2integers1 and integers2 are not equal

Size of DoubleSubscriptedArray integers3 is 2 X 4DoubleSubscriptedArray after initialization:10 11 12 13 14 15 16 17

Assigning integers2 to integers1:integers1:18 19 20 21 22 23 24 25 26

integers2:18 19 20 21 22 23 24 25 26

Evaluating: integers1 == integers2integers1 and integers2 are equal

integers1( 1, 2 ) is 23

Assigning 1000 to integers1( 1, 2 )integers1:18 19 20 21 22 1000 24 25 26

Attempt to assign 1000 to integers1( 15, 2 )

Error: One or both subscripts out of range

cpphtp5_11_IM.fm Page 582 Thursday, December 23, 2004 4:15 PM

Page 13: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 583

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.12 Overload the subscript operator to return the largest element of a collection, the secondlargest, the third largest, and so on.

11.13 Consider class Complex shown in Figs. 11.19–11.21. The class enables operations on so-called complex numbers. These are numbers of the form realPart + imaginaryPart * i, where i hasthe value

a) Modify the class to enable input and output of complex numbers through the over-loaded >> and << operators, respectively (you should remove the print function fromthe class).

b) Overload the multiplication operator to enable multiplication of two complex numbersas in algebra.

c) Overload the == and != operators to allow comparisons of complex numbers.

1 // Fig. 11.19: Complex.h2 // Complex class definition.3 #ifndef COMPLEX_H4 #define COMPLEX_H56 class Complex7 {8 public:9 Complex( double = 0.0, double = 0.0 ); // constructor

10 Complex operator+( const Complex & ) const; // addition11 Complex operator-( const Complex & ) const; // subtraction12 void print() const; // output13 private:14 double real; // real part15 double imaginary; // imaginary part16 }; // end class Complex1718 #endif

Fig. 11.19 | Complex class definition.

1 // Fig. 11.20: Complex.cpp2 // Complex class member-function definitions.3 #include <iostream>4 using std::cout;56 #include "Complex.h" // Complex class definition78 // Constructor9 Complex::Complex( double realPart, double imaginaryPart )

Fig. 11.20 | Complex class member-function definitions. (Part 1 of 2.)

1–

cpphtp5_11_IM.fm Page 583 Thursday, December 23, 2004 4:15 PM

Page 14: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

584 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

10 : real( realPart ),11 imaginary( imaginaryPart ) 12 { 13 // empty body14 } // end Complex constructor1516 // addition operator17 Complex Complex::operator+( const Complex &operand2 ) const18 {19 return Complex( real + operand2.real, 20 imaginary + operand2.imaginary );21 } // end function operator+2223 // subtraction operator24 Complex Complex::operator-( const Complex &operand2 ) const25 {26 return Complex( real - operand2.real, 27 imaginary - operand2.imaginary );28 } // end function operator-2930 // display a Complex object in the form: (a, b)31 void Complex::print() const32 { 33 cout << '(' << real << ", " << imaginary << ')';34 } // end function print

1 // Fig. 11.21: fig11_21.cpp2 // Complex class test program.3 #include <iostream>4 using std::cout;5 using std::endl;67 #include "Complex.h"89 int main()

10 {11 Complex x;12 Complex y( 4.3, 8.2 );13 Complex z( 3.3, 1.1 );1415 cout << "x: ";16 x.print();17 cout << "\ny: ";18 y.print();19 cout << "\nz: ";20 z.print();21

Fig. 11.21 | Complex numbers. (Part 1 of 2.)

Fig. 11.20 | Complex class member-function definitions. (Part 2 of 2.)

cpphtp5_11_IM.fm Page 584 Thursday, December 23, 2004 4:15 PM

Page 15: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 585

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

ANS: [Note: In the solution below, the == operator returns true by comparing double val-ues—a practice that is error-prone due to the way computers handle floating-pointvalues. You may want to modify the == operator to take the difference between twodoubles and determining if the difference is less than a threshold value such as0.00001.]

22 x = y + z;23 cout << "\n\nx = y + z:" << endl;24 x.print();25 cout << " = ";26 y.print();27 cout << " + ";28 z.print();2930 x = y - z;31 cout << "\n\nx = y - z:" << endl;32 x.print();33 cout << " = ";34 y.print();35 cout << " - ";36 z.print();37 cout << endl;38 return 0;39 } // end main

x: (0, 0)y: (4.3, 8.2)z: (3.3, 1.1)

x = y + z:(7.6, 9.3) = (4.3, 8.2) + (3.3, 1.1)

x = y - z:(1, 7.1) = (4.3, 8.2) - (3.3, 1.1)

1 // Exercise 11.13 Solution: Complex.h2 // Complex class definition.3 #ifndef COMPLEX_H4 #define COMPLEX_H56 #include <iostream>7 using std::ostream;8 using std::istream;9

10 class Complex11 {12 friend ostream &operator<<( ostream &, const Complex & );13 friend istream &operator>>( istream &, Complex & );14 public:

Fig. 11.21 | Complex numbers. (Part 2 of 2.)

cpphtp5_11_IM.fm Page 585 Thursday, December 23, 2004 4:15 PM

Page 16: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

586 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

15 Complex( double = 0.0, double = 0.0 ); // constructor16 Complex operator+( const Complex& ) const; // addition17 Complex operator-( const Complex& ) const; // subtraction18 Complex operator*( const Complex& ) const; // multiplication19 Complex& operator=( const Complex& ); // assignment20 bool operator==( const Complex& ) const;21 bool operator!=( const Complex& ) const;22 private:23 double real; // real part24 double imaginary; // imaginary part25 }; // end class Complex2627 #endif

1 // Exercise 11.13 Solution: Complex.cpp2 // Complex class member-function definitions.3 #include "Complex.h"45 #include <iostream>6 using std::ostream;7 using std::istream;89 // Constructor

10 Complex::Complex( double realPart, double imaginaryPart )11 : real( realPart ),12 imaginary( imaginaryPart )13 {14 // empty body15 } // end Complex constructor1617 // addition operator18 Complex Complex::operator+( const Complex &operand2 ) const19 {20 return Complex( real + operand2.real,21 imaginary + operand2.imaginary );22 } // end function operator+2324 // subtraction operator25 Complex Complex::operator-( const Complex &operand2 ) const26 {27 return Complex( real - operand2.real,28 imaginary - operand2.imaginary );29 } // end function operator-3031 // Overloaded multiplication operator32 Complex Complex::operator*( const Complex &operand2 ) const33 {34 return Complex(35 ( real * operand2.real ) + ( imaginary * operand2.imaginary ),36 ( real * operand2.imaginary ) + ( imaginary * operand2.real ) );37 } // end function operator*3839 // Overloaded = operator40 Complex& Complex::operator=( const Complex &right )

cpphtp5_11_IM.fm Page 586 Thursday, December 23, 2004 4:15 PM

Page 17: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 587

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

41 {42 real = right.real;43 imaginary = right.imaginary;44 return *this; // enables concatenation45 } // end function operator=4647 bool Complex::operator==( const Complex &right ) const48 { 49 return ( right.real == real ) && ( right.imaginary == imaginary )50 ? true : false; 51 } // end function operator== 5253 bool Complex::operator!=( const Complex &right ) const54 {55 return !( *this == right ); 56 } // end function operator!=5758 ostream& operator<<( ostream &output, const Complex &complex )59 {60 output << "(" << complex.real << ", " << complex.imaginary << ")";61 return output;62 } // end function operator<<6364 istream& operator>>( istream &input, Complex &complex )65 {66 input.ignore(); // skip (67 input >> complex.real;68 input.ignore( 2 ); // skip ',' and space69 input >> complex.imaginary;70 input.ignore(); // skip )71 return input;72 } // end function operator>>

1 // Exercise 11.13 Solution: ex11_13.cpp2 // Complex class test program.3 #include <iostream>4 using std::cout;5 using std::cin;67 #include "Complex.h"89 int main()

10 {11 Complex x, y( 4.3, 8.2 ), z( 3.3, 1.1 ), k;1213 cout << "Enter a complex number in the form: (a, b)\n? ";14 cin >> k; // demonstrating overloaded >>15 cout << "x: " << x << "\ny: " << y << "\nz: " << z << "\nk: "16 << k << '\n'; // demonstrating overloaded <<17 x = y + z; // demonstrating overloaded + and =18 cout << "\nx = y + z:\n" << x << " = " << y << " + " << z << '\n';19 x = y - z; // demonstrating overloaded - and =20 cout << "\nx = y - z:\n" << x << " = " << y << " - " << z << '\n';21 x = y * z; // demonstrating overloaded * and =

cpphtp5_11_IM.fm Page 587 Thursday, December 23, 2004 4:15 PM

Page 18: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

588 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.14 A machine with 32-bit integers can represent integers in the range of approximately –2 bil-lion to +2 billion. This fixed-size restriction is rarely troublesome, but there are applications inwhich we would like to be able to use a much wider range of integers. This is what C++ was builtto do, namely, create powerful new data types. Consider class HugeInt of Figs. 11.22–11.24. Studythe class carefully, then answer the following:

a) Describe precisely how it operates.b) What restrictions does the class have?c) Overload the * multiplication operator.d) Overload the / division operator.e) Overload all the relational and equality operators.

[Note: We do not show an assignment operator or copy constructor for class HugeInteger, becausethe assignment operator and copy constructor provided by the compiler are capable of copying theentire array data member properly.]

22 cout << "\nx = y * z:\n" << x << " = " << y << " * " << z << "\n\n";2324 if ( x != k ) // demonstrating overloaded !=25 cout << x << " != " << k << '\n';2627 cout << '\n';28 x = k;2930 if ( x == k ) // demonstrating overloaded ==31 cout << x << " == " << k << '\n';3233 return 0;34 } // end main

Enter a complex number in the form: (a, b)? (0, 0)x: (0, 0)y: (4.3, 8.2)z: (3.3, 1.1)k: (0, 0)

x = y + z:(7.6, 9.3) = (4.3, 8.2) + (3.3, 1.1)

x = y - z:(1, 7.1) = (4.3, 8.2) - (3.3, 1.1)

x = y * z:(23.21, 31.79) = (4.3, 8.2) * (3.3, 1.1)

(23.21, 31.79) != (0, 0)

(0, 0) == (0, 0)

1 // Fig. 11.22: Hugeint.h

Fig. 11.22 | HugeInt class definition. (Part 1 of 2.)

cpphtp5_11_IM.fm Page 588 Thursday, December 23, 2004 4:15 PM

Page 19: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 589

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

2 // HugeInt class definition.3 #ifndef HUGEINT_H4 #define HUGEINT_H56 #include <iostream>7 using std::ostream;89 class HugeInt

10 {11 friend ostream &operator<<( ostream &, const HugeInt & );12 public:13 HugeInt( long = 0 ); // conversion/default constructor14 HugeInt( const char * ); // conversion constructor1516 // addition operator; HugeInt + HugeInt17 HugeInt operator+( const HugeInt & ) const;1819 // addition operator; HugeInt + int20 HugeInt operator+( int ) const;2122 // addition operator; 23 // HugeInt + string that represents large integer value24 HugeInt operator+( const char * ) const;25 private:26 short integer[ 30 ];27 }; // end class HugetInt2829 #endif

1 // Fig. 11.23: Hugeint.cpp 2 // HugeInt member-function and friend-function definitions.3 #include <cctype> // isdigit function prototype4 #include <cstring> // strlen function prototype5 #include "Hugeint.h" // HugeInt class definition67 // default constructor; conversion constructor that converts8 // a long integer into a HugeInt object9 HugeInt::HugeInt( long value )

10 {11 // initialize array to zero12 for ( int i = 0; i <= 29; i++ )13 integer[ i ] = 0; 1415 // place digits of argument into array 16 for ( int j = 29; value != 0 && j >= 0; j-- )17 {18 integer[ j ] = value % 10;

Fig. 11.23 | HugeInt class member-function and friend-function definitions. (Part 1 of 3.)

Fig. 11.22 | HugeInt class definition. (Part 2 of 2.)

cpphtp5_11_IM.fm Page 589 Thursday, December 23, 2004 4:15 PM

Page 20: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

590 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

19 value /= 10;20 } // end for21 } // end HugeInt default/conversion constructor2223 // conversion constructor that converts a character string 24 // representing a large integer into a HugeInt object25 HugeInt::HugeInt( const char *string )26 {27 // initialize array to zero28 for ( int i = 0; i <= 29; i++ )29 integer[ i ] = 0;3031 // place digits of argument into array32 int length = strlen( string );3334 for ( int j = 30 - length, k = 0; j <= 29; j++, k++ )3536 if ( isdigit( string[ k ] ) )37 integer[ j ] = string[ k ] - '0';38 } // end HugeInt conversion constructor3940 // addition operator; HugeInt + HugeInt41 HugeInt HugeInt::operator+( const HugeInt &op2 ) const42 {43 HugeInt temp; // temporary result44 int carry = 0;4546 for ( int i = 29; i >= 0; i-- )47 {48 temp.integer[ i ] = 49 integer[ i ] + op2.integer[ i ] + carry;5051 // determine whether to carry a 152 if ( temp.integer[ i ] > 9 )53 {54 temp.integer[ i ] %= 10; // reduce to 0-955 carry = 1;56 } // end if57 else // no carry 58 carry = 0;59 } // end for6061 return temp; // return copy of temporary object62 } // end function operator+6364 // addition operator; HugeInt + int65 HugeInt HugeInt::operator+( int op2 ) const66 { 67 // convert op2 to a HugeInt, then invoke 68 // operator+ for two HugeInt objects69 return *this + HugeInt( op2 ); 70 } // end function operator+7172 // addition operator;

Fig. 11.23 | HugeInt class member-function and friend-function definitions. (Part 2 of 3.)

cpphtp5_11_IM.fm Page 590 Thursday, December 23, 2004 4:15 PM

Page 21: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 591

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

73 // HugeInt + string that represents large integer value74 HugeInt HugeInt::operator+( const char *op2 ) const75 { 76 // convert op2 to a HugeInt, then invoke 77 // operator+ for two HugeInt objects78 return *this + HugeInt( op2 ); 79 } // end operator+8081 // overloaded output operator82 ostream& operator<<( ostream &output, const HugeInt &num )83 {84 int i;8586 for ( i = 0; ( num.integer[ i ] == 0 ) && ( i <= 29 ); i++ )87 ; // skip leading zeros8889 if ( i == 30 )90 output << 0;91 else9293 for ( ; i <= 29; i++ )94 output << num.integer[ i ];9596 return output;97 } // end function operator<<

1 // Fig. 11.24: fig11_24.cpp2 // HugeInt test program.3 #include <iostream>4 using std::cout;5 using std::endl;67 #include "Hugeint.h"89 int main()

10 {11 HugeInt n1( 7654321 );12 HugeInt n2( 7891234 );13 HugeInt n3( "99999999999999999999999999999" );14 HugeInt n4( "1" );15 HugeInt n5;1617 cout << "n1 is " << n1 << "\nn2 is " << n218 << "\nn3 is " << n3 << "\nn4 is " << n419 << "\nn5 is " << n5 << "\n\n";2021 n5 = n1 + n2;

Fig. 11.24 | Huge integers. (Part 1 of 2.)

Fig. 11.23 | HugeInt class member-function and friend-function definitions. (Part 3 of 3.)

cpphtp5_11_IM.fm Page 591 Thursday, December 23, 2004 4:15 PM

Page 22: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

592 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

ANS: [Note: This solution, as it is based on the code above, does not handle negative values,or cases when a value causes overflow. Also, the solution overloads the - operator, butthis is not necessary—students need to implement subtraction of HugeInts to imple-ment division, but they can use a private helper function if they wish.]

22 cout << n1 << " + " << n2 << " = " << n5 << "\n\n";2324 cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";2526 n5 = n1 + 9;27 cout << n1 << " + " << 9 << " = " << n5 << "\n\n";2829 n5 = n2 + "10000";30 cout << n2 << " + " << "10000" << " = " << n5 << endl;31 return 0;32 } // end main

n1 is 7654321n2 is 7891234n3 is 99999999999999999999999999999n4 is 1n5 is 0

7654321 + 7891234 = 15545555

99999999999999999999999999999 + 1= 100000000000000000000000000000

7654321 + 9 = 7654330

7891234 + 10000 = 7901234

1 // Fig. 11.22: Hugeint.h 2 // HugeInt class definition.3 #ifndef HUGEINT_H4 #define HUGEINT_H56 #include <iostream>7 using std::ostream;89 class HugeInt

10 {11 friend ostream &operator<<( ostream &, const HugeInt & );12 public:13 HugeInt( long = 0 ); // conversion/default constructor14 HugeInt( const char * ); // conversion constructor1516 // addition operator; HugeInt + HugeInt17 HugeInt operator+( const HugeInt & ) const;

Fig. 11.24 | Huge integers. (Part 2 of 2.)

cpphtp5_11_IM.fm Page 592 Thursday, December 23, 2004 4:15 PM

Page 23: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 593

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

1819 // addition operator; HugeInt + int20 HugeInt operator+( int ) const; 2122 // addition operator; 23 // HugeInt + string that represents large integer value24 HugeInt operator+( const char * ) const;2526 bool operator==( const HugeInt & ) const; // equality operator27 bool operator!=( const HugeInt & ) const; // inequality operator28 bool operator<( const HugeInt & ) const; // less than operator2930 // less than or equal to operator31 bool operator<=( const HugeInt & ) const; 32 bool operator>( const HugeInt & ) const; // greater than operator3334 // greater than or equal to operator35 bool operator>=( const HugeInt & ) const;36 HugeInt operator-( const HugeInt & ) const; // subtraction operator37 HugeInt operator*( const HugeInt & ) const; // multiply two HugeInts38 HugeInt operator/( const HugeInt & ) const; // divide two HugeInts3940 int getLength() const;41 private:42 short integer[ 30 ];43 }; // end class HugeInt4445 #endif

1 // Fig. 11.23: Hugeint.cpp 2 // HugeInt member-function and friend-function definitions.3 #include <iostream>4 using std::cout;5 using std::endl;67 #include <cctype> // isdigit function prototype8 using std::isdigit;9

10 #include <cstring> // strlen function prototype11 using std::strlen;1213 #include "Hugeint.h" // HugeInt class definition1415 // default constructor; conversion constructor that converts16 // a long integer into a HugeInt object17 HugeInt::HugeInt( long value )18 {19 // initialize array to zero20 for ( int i = 0; i <= 29; i++ )21 integer[ i ] = 0; 2223 // place digits of argument into array

cpphtp5_11_IM.fm Page 593 Thursday, December 23, 2004 4:15 PM

Page 24: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

594 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

24 for ( int j = 29; value != 0 && j >= 0; j-- )25 {26 integer[ j ] = value % 10;27 value /= 10;28 } // end for29 } // end HugeInt default/conversion constructor3031 // conversion constructor that converts a character string 32 // representing a large integer into a HugeInt object33 HugeInt::HugeInt( const char *string )34 {35 // initialize array to zero36 for ( int i = 0; i <= 29; i++ )37 integer[ i ] = 0;3839 // place digits of argument into array40 int length = strlen( string );4142 for ( int j = 30 - length, k = 0; j <= 29; j++, k++ )4344 if ( isdigit( string[ k ] ) )45 integer[ j ] = string[ k ] - '0';4647 } // end HugeInt conversion constructor4849 // get function calculates length of integer50 int HugeInt::getLength() const51 {52 for ( int i = 0; i <= 29; i++ )53 if ( integer[ i ] != 0 )54 break; // break when first digit is reached55 56 return 30 - i; // length is from first digit (at i) to end of array57 } // end function getLength5859 // addition operator; HugeInt + HugeInt60 HugeInt HugeInt::operator+( const HugeInt &op2 ) const61 {62 HugeInt temp; // temporary result63 int carry = 0;6465 for ( int i = 29; i >= 0; i-- )66 {67 temp.integer[ i ] = 68 integer[ i ] + op2.integer[ i ] + carry;6970 // determine whether to carry a 171 if ( temp.integer[ i ] > 9 )72 {73 temp.integer[ i ] %= 10; // reduce to 0-974 carry = 1;75 } // end if76 else // no carry 77 carry = 0;78 } // end for

cpphtp5_11_IM.fm Page 594 Thursday, December 23, 2004 4:15 PM

Page 25: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 595

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

7980 return temp; // return copy of temporary object81 } // end function operator+8283 // addition operator; HugeInt + int84 HugeInt HugeInt::operator+( int op2 ) const85 { 86 // convert op2 to a HugeInt, then invoke 87 // operator+ for two HugeInt objects88 return *this + HugeInt( op2 ); 89 } // end function operator+9091 // addition operator;92 // HugeInt + string that represents large integer value93 HugeInt HugeInt::operator+( const char *op2 ) const 94 { 95 // convert op2 to a HugeInt, then invoke 96 // operator+ for two HugeInt objects97 return *this + HugeInt( op2 ); 98 } // end function operator+99100 // equality operator; HugeInt == HugeInt101 bool HugeInt::operator==( const HugeInt &op2 ) const102 {103 for ( int i = 0; i < 30; i++ ) // compare each element104 if ( op2.integer[ i ] != integer[ i ] )105 return false; // return false if mismatch found106 107 return true; // all elements match, return true108 } // end function operator==109110 // inequality operator; HugeInt != HugeInt111 bool HugeInt::operator!=( const HugeInt &op2 ) const112 {113 return !( *this == op2 ); // return opposite of ==114 } // end function operator!=115116 // less than operator; HugeInt < HugeInt117 bool HugeInt::operator<( const HugeInt &op2 ) const118 {119 for ( int i = 0; i < 30; i++ ) // compare each element120 {121 if ( integer[ i ] == op2.integer[ i ] )122 continue; // test next element123 else if ( integer[ i ] > op2.integer[ i ] )124 return false; // first element larger125 else126 return true; // first element smaller127 } // end for128129 return false; // if reached this point, objects are equal130 } // end function operator<131132 // less than or equal operator; HugeInt <= HugeInt133 bool HugeInt::operator<=( const HugeInt &op2 ) const

cpphtp5_11_IM.fm Page 595 Thursday, December 23, 2004 4:15 PM

Page 26: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

596 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

134 {135 return ( ( *this == op2 ) || ( *this < op2 ) );136 } // end function operator<=137138 // greater than operator; HugeInt > HugeInt139 bool HugeInt::operator>( const HugeInt &op2 ) const140 {141 return !( *this <= op2 );142 } // end function operator>143144 // greater than or equal operator; HugeInt >= HugeInt145 bool HugeInt::operator>=( const HugeInt &op2 ) const146 {147 return ( ( *this == op2 ) || ( *this > op2 ) );148 } // end function operator>=149150 // overloaded output operator151 ostream& operator<<( ostream &output, const HugeInt &num )152 {153 int i;154155 for ( i = 0; ( num.integer[ i ] == 0 ) && ( i <= 29 ); i++ )156 ; // skip leading zeros157158 if ( i == 30 )159 output << 0;160 else161162 for ( ; i <= 29; i++ )163 output << num.integer[ i ];164165 return output;166 } // end function operator<<167168 // subtraction operator, subtract op2 from (*this)169 HugeInt HugeInt::operator-( const HugeInt &op2 ) const170 {171 // return if first value is smaller; we are not handling negatives172 if ( op2 > ( *this ) ) 173 {174 cout << "Error: Tried to subtract larger value from smaller value."175 << endl;176 return HugeInt( "0" );177 } // end if178179 HugeInt result( "0" ); // final result currently 0180181 // used to determine if previous digit had 10 added to it;182 // if true, current digit needs to be reduced by 1183 bool minusOne = false;184185 // for each digit in both arrays,186 // subtract digit of smaller int from digit of larger int187 for ( int i = 29; i >= 0; i-- )188 {

cpphtp5_11_IM.fm Page 596 Thursday, December 23, 2004 4:15 PM

Page 27: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 597

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

189 // find digits we will currently be subtracting190 int topValue = ( *this ).integer[ i ];191 int bottomValue = op2.integer[ i ];192193 // if previous topValue had 10 added to it;194 // subtract one from current topValue195 if ( minusOne ) 196 {197 if ( topValue == 0 ) // topValue cannot become -1198199 // set to 9 but keep minusOne true for next digit200 topValue = 9; 201 else202 {203 topValue -= 1; // subtract from top value204 minusOne = false; // minusOne is handled, return to false205 } // end else206 } // end outer if207208 if ( topValue >= bottomValue ) 209210 // if topValue larger, perform subtraction and store result211 result.integer[ i ] = topValue - bottomValue;212 else213 {214 topValue += 10; // if bottomValue larger, add 10 to topValue215 minusOne = true; // next digit must be decreased216217 // topValue is now larger, perform subtraction and store result218 result.integer[ i ] = topValue - bottomValue;219 } // end else220 } // end for221222 return result; // return final result223 } // end function operator-224225 // multiplication operator; multiply op2 with (*this)226 HugeInt HugeInt::operator*( const HugeInt &op2 ) const227 {228 int carryOver = 0; // carry value when previous digits are multiplied229 HugeInt total( "0" ); // result currently 0230231 // find the smaller int232 HugeInt smaller = ( *this < op2 ) ? *this : op2;233 HugeInt larger = ( *this > op2 ) ? *this : op2;234235 // determine index of larger's first digit; used to determine236 // when to stop multiplying237 for ( int x = 0; ( x <= 29 ) && ( larger.integer[ x ] == 0 ); x++ ) ;238 int indexOfFirstDigitForLarger = x;239240 // for each digit in smaller, multiply by each digit in larger241 for ( int i = 30; i > 30 - smaller.getLength(); i-- )242 {243 // currentInt stores result of current digit in

cpphtp5_11_IM.fm Page 597 Thursday, December 23, 2004 4:15 PM

Page 28: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

598 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

244 // smaller multiplied by digits in larger245 HugeInt currentInt( "0" );246247 // currentIntFrontHandle used to keep track of248 // index of first digit in currentInt249 int currentIntFrontHandle = i - 1;250251 // multiply each digit in larger with the current digit in smaller;252 // go backwards from last digit in larger to first digit253 for ( int j = 30; j > 30 - larger.getLength(); j-- )254 {255 // perform multiplication;256 // add carryOver from previous multiplications257 int currentResult = carryOver + 258 ( larger.integer[ j - 1 ] * smaller.integer[ i - 1 ] );259260 // if we have reached the first digit of larger261 if ( j - 1 == indexOfFirstDigitForLarger )262 {263 carryOver = 0; // no more carryOver required264265 // store two digits at beginning of currentInt, update handle266 currentInt.integer[ currentIntFrontHandle ] =267 currentResult % 10;268 currentIntFrontHandle -= 1;269 currentInt.integer[ currentIntFrontHandle ] =270 currentResult / 10;271 currentIntFrontHandle -= 1;272 } // end if273 else274 {275 // carryOver is first digit when currentResult > 10276 carryOver = currentResult / 10;277278 // store remaining digit in current result; update handle279 currentInt.integer[ currentIntFrontHandle ] =280 currentResult % 10;281 currentIntFrontHandle -= 1;282 } // end else283 } // end inner for284285 total = total + currentInt; // add current result to running total286 } // end outer for287288 return total; // return product289 } // end function operator*290291 // division operator; divide op2 by (*this)292 HugeInt HugeInt::operator/( const HugeInt &op2 ) const293 {294 // use copy constructor to create remainderIntegers;295 // remainderIntegers used to add digits to remainders296 HugeInt remainderIntegers( *this );297298 // contains portion of (*this)

cpphtp5_11_IM.fm Page 598 Thursday, December 23, 2004 4:15 PM

Page 29: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 599

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

299 HugeInt currentValue( "0" ); 300 HugeInt result( "0" ); // final result, 0 for now301302 // solution will not be longer than original value being divided303 int maxSolutionLength = ( *this ).getLength();304305 // for each digit in value being divided306 for ( int i = 30 - maxSolutionLength; i < 30; i++ )307 {308 // add remainder to end of current value309 currentValue = currentValue * HugeInt( "10" );310 currentValue.integer[ 29 ] = remainderIntegers.integer[ i ];311312 HugeInt tempResult( "0" ); // result of currentValue divided by op2313314 if ( op2 > currentValue )315316 // store result of op2 / currentValue317 result.integer[ i ] = 0;318 else319 {320 // op2 / currentValue cannot be greater than 9;321 // use loop to determine what solution is322 for ( int j = 1; j <= 10; j++ )323 {324 HugeInt tempProduct = op2 * HugeInt( j );325326 // if op2 * HugeInt( j ) is greater than currentValue,327 // then op2 / currentValue is the value of j - 1328 if ( tempProduct > currentValue )329 break;330 } // end for331332 result.integer[ i ] = j - 1; // result of op2 / currentValue333334 // product used to determine next value that must be divided335 tempResult = op2 * HugeInt( j - 1 );336 } // end else337338 // subtract tempResult to get remainder used to continue division339 currentValue = currentValue - tempResult;340 } // end for341342 return result;343 } // end function operator/

1 // Exercise 11.14 Solution: ex11_14.cpp2 // HugeInt test program.3 #include <iostream>4 using std::cout;5 using std::endl;6

cpphtp5_11_IM.fm Page 599 Thursday, December 23, 2004 4:15 PM

Page 30: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

600 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

7 #include "Hugeint.h"89 int main()

10 {11 HugeInt n1( 7654321 );12 HugeInt n2( 7891234 );13 HugeInt n3( "99999999999999999999999999999" );14 HugeInt n4( "1" );15 HugeInt n5( "12341234" );16 HugeInt n6( "7888" );17 HugeInt result;1819 cout << "n1 is " << n1 << "\nn2 is " << n220 << "\nn3 is " << n3 << "\nn4 is " << n421 << "\nn5 is " << n5 << "\nn6 is " << n622 << "\nresult is " << result << "\n\n";2324 // test relational and equality operators25 if ( n1 == n2 )26 cout << "n1 equals n2" << endl;2728 if ( n1 != n2 )29 cout << "n1 is not equal to n2" << endl;3031 if ( n1 < n2 )32 cout << "n1 is less than n2" << endl;3334 if ( n1 <= n2 )35 cout << "n1 is less than or equal to n2" << endl;3637 if ( n1 > n2 )38 cout << "n1 is greater than n2" << endl;3940 if ( n1 >= n2 )41 cout << "n1 is greater than or equal to n2" << endl;4243 result = n1 + n2;44 cout << n1 << " + " << n2 << " = " << result << "\n\n";4546 cout << n3 << " + " << n4 << "\n= " << ( n3 + n4 ) << "\n\n";4748 result = n1 + 9;49 cout << n1 << " + " << 9 << " = " << result << endl;5051 result = n2 + "10000";52 cout << n2 << " + " << "10000" << " = " << result << endl;5354 result = n5 * n6;55 cout << n5 << " * " << n6 << " = " << result << endl;5657 result = n5 - n6;58 cout << n5 << " - " << n6 << " = " << result << endl;5960 result = n5 / n6;61 cout << n5 << " / " << n6 << " = " << result << endl;

cpphtp5_11_IM.fm Page 600 Thursday, December 23, 2004 4:15 PM

Page 31: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 601

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.15 Create a class RationalNumber (fractions) with the following capabilities:a) Create a constructor that prevents a 0 denominator in a fraction, reduces or simplifies

fractions that are not in reduced form and avoids negative denominators.b) Overload the addition, subtraction, multiplication and division operators for this class.c) Overload the relational and equality operators for this class.ANS:

62 return 0;63 } // end main

n1 is 7654321n2 is 7891234n3 is 99999999999999999999999999999n4 is 1n5 is 12341234n6 is 7888result is 0

n1 is not equal to n2n1 is less than n2n1 is less than or equal to n27654321 + 7891234 = 15545555

99999999999999999999999999999 + 1= 100000000000000000000000000000

7654321 + 9 = 76543307891234 + 10000 = 790123412341234 * 7888 = 9734765379212341234 - 7888 = 1233334612341234 / 7888 = 1564

1 // Exercise 11.15 Solution: RationalNumber.h2 // RationalNumber class definition.3 #ifndef RATIONAL_NUMBER_H4 #define RATIONAL_NUMBER_H56 class RationalNumber7 {8 public:9 RationalNumber( int = 0, int = 1 ); // default constructor

10 RationalNumber operator+( const RationalNumber& ); // addition11 RationalNumber operator-( const RationalNumber& ); // subtraction12 RationalNumber operator*( const RationalNumber& ); // multiplication13 RationalNumber operator/( RationalNumber& ); // division14 15 // relational operators16 bool operator>( const RationalNumber& ) const;17 bool operator<( const RationalNumber& ) const;18 bool operator>=( const RationalNumber& ) const;19 bool operator<=( const RationalNumber& ) const;20

cpphtp5_11_IM.fm Page 601 Thursday, December 23, 2004 4:15 PM

Page 32: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

602 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

21 // equality operators22 bool operator==( const RationalNumber& ) const;23 bool operator!=( const RationalNumber& ) const; 24 25 void printRational() const; // display rational number26 private:27 int numerator; // private variable numerator28 int denominator; // private variable denominator29 void reduction(); // function for fraction reduction30 }; // end class RationalNumber3132 #endif

1 // Exercise 11.15 Solution: RationalNumber.cpp2 // RationalNumber member-function definitions.3 #include <cstdlib>4 using std::exit;56 #include <iostream> 7 using std::cout; 8 using std::endl; 9

10 #include "RationalNumber.h"1112 // RationalNumber constructor sets n and d and calls reduction13 RationalNumber::RationalNumber( int n, int d )14 {15 numerator = n;16 denominator = ( d > 0 ) ? d : 1; // validate denominator, 1 as default17 reduction(); // invokes function reduction18 } // end RationalNumber constructor1920 // overloaded + operator21 RationalNumber RationalNumber::operator+( const RationalNumber &a ) 22 {23 return RationalNumber( 24 numerator * a.denominator + denominator * a.numerator,25 denominator * a.denominator );26 } // end function operator+2728 // overloaded - operator29 RationalNumber RationalNumber::operator-( const RationalNumber &s )30 {31 return RationalNumber( 32 numerator * s.denominator - denominator * s.numerator,33 denominator * s.denominator );34 } // end function operator-3536 // overloaded * operator37 RationalNumber RationalNumber::operator*( const RationalNumber &m )38 {39 return RationalNumber( numerator * m.numerator,40 denominator * m.denominator );41 } // end function operator*

cpphtp5_11_IM.fm Page 602 Thursday, December 23, 2004 4:15 PM

Page 33: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 603

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

4243 // overloaded / operator44 RationalNumber RationalNumber::operator/( RationalNumber &d )45 {46 RationalNumber divide;4748 if ( d.numerator != 0 ) // check for a zero in numerator49 {50 return RationalNumber( numerator * d.denominator,51 denominator * d.numerator );52 }53 else54 {55 cout << "Divide by zero error: terminating program" << endl;56 exit( 1 ); // stdlib function57 } // end if/else structure58 } // end function operator/5960 // overloaded > operator61 bool RationalNumber::operator>( const RationalNumber &gr ) const62 {63 if ( static_cast< double >( numerator ) / denominator > 64 static_cast< double >( gr.numerator ) / gr.denominator )65 return true;66 else67 return false;68 } // end function operator>6970 // overloaded < operator71 bool RationalNumber::operator<( const RationalNumber &lr ) const72 {73 if ( static_cast< double >( numerator ) / denominator < 74 static_cast< double >( lr.numerator ) / lr.denominator )75 return true;76 else77 return false;78 } // end function operator<7980 // overloaded >= operator81 bool RationalNumber::operator>=( const RationalNumber &ger ) const82 {83 return *this == ger || *this > ger;84 } // end function operator>=8586 // overloaded <= operator87 bool RationalNumber::operator<=( const RationalNumber &ler ) const88 89 { 90 return *this == ler || *this < ler;91 } // end function operator<=9293 // overloaded == operator94 bool RationalNumber::operator==( const RationalNumber &er ) const95 {96 if ( numerator == er.numerator && denominator == er.denominator )

cpphtp5_11_IM.fm Page 603 Thursday, December 23, 2004 4:15 PM

Page 34: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

604 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

97 return true;98 else99 return false;100 } // end function operator==101102 // overloaded != operator103 bool RationalNumber::operator!=( const RationalNumber &ner ) const104 { 105 return !( *this == ner );106 } // end function operator!=107108 // function printRational definition109 void RationalNumber::printRational() const110 {111 if ( numerator == 0 ) // print fraction as zero112 cout << numerator;113 else if ( denominator == 1 ) // print fraction as integer114 cout << numerator;115 else116 cout << numerator << '/' << denominator;117 } // end function printRational118119 // function reduction definition120 void RationalNumber::reduction()121 {122 int largest, gcd = 1; // greatest common divisor;123124 largest = ( numerator > denominator ) ? numerator: denominator;125126 for ( int loop = 2; loop <= largest; loop++ )127 if ( numerator % loop == 0 && denominator % loop == 0 )128 gcd = loop;129130 numerator /= gcd;131 denominator /= gcd;132 } // end function reduction

1 // Exercise 11.15 Solution: ex11_15.cpp2 // RationalNumber test program.3 #include <iostream> 4 using std::cout;5 using std::endl;67 #include "RationalNumber.h"89 int main()

10 {11 RationalNumber c( 7, 3 ), d( 3, 9 ), x;1213 c.printRational();14 cout << " + " ;15 d.printRational();16 cout << " = ";17 x = c + d; // test overloaded operators + and =

cpphtp5_11_IM.fm Page 604 Thursday, December 23, 2004 4:15 PM

Page 35: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 605

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

18 x.printRational();1920 cout << '\n';21 c.printRational();22 cout << " - " ;23 d.printRational();24 cout << " = ";25 x = c - d; // test overloaded operators - and =26 x.printRational();2728 cout << '\n';29 c.printRational();30 cout << " * " ;31 d.printRational();32 cout << " = ";33 x = c * d; // test overloaded operators * and =34 x.printRational();3536 cout << '\n';37 c.printRational();38 cout << " / " ;39 d.printRational();40 cout << " = ";41 x = c / d; // test overloaded operators / and =42 x.printRational();4344 cout << '\n';45 c.printRational();46 cout << " is:\n";4748 // test overloaded greater than operator49 cout << ( ( c > d ) ? " > " : " <= " );50 d.printRational();51 cout << " according to the overloaded > operator\n";5253 // test overloaded less than operator54 cout << ( ( c < d ) ? " < " : " >= " );55 d.printRational();56 cout << " according to the overloaded < operator\n";5758 // test overloaded greater than or equal to operator59 cout << ( ( c >= d ) ? " >= " : " < " );60 d.printRational();61 cout << " according to the overloaded >= operator\n";6263 // test overloaded less than or equal to operator64 cout << ( ( c <= d ) ? " <= " : " > " );65 d.printRational();66 cout << " according to the overloaded <= operator\n";67 68 // test overloaded equality operator69 cout << ( ( c == d ) ? " == " : " != " );70 d.printRational();71 cout << " according to the overloaded == operator\n";72

cpphtp5_11_IM.fm Page 605 Thursday, December 23, 2004 4:15 PM

Page 36: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

606 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.16 Study the C string-handling library functions and implement each of the functions as partof class String (Figs. 11.9–11.10). Then, use these functions to perform text manipulations.

11.17 Develop class Polynomial. The internal representation of a Polynomial is an array of terms.Each term contains a coefficient and an exponent. The term

2x4

has the coefficient 2 and the exponent 4. Develop a complete class containing proper constructorand destructor functions as well as set and get functions. The class should also provide the followingoverloaded operator capabilities:

a) Overload the addition operator (+) to add two Polynomials.b) Overload the subtraction operator (-) to subtract two Polynomials.c) Overload the assignment operator to assign one Polynomial to another.d) Overload the multiplication operator (*) to multiply two Polynomials.e) Overload the addition assignment operator (+=), subtraction assignment operator (-=),

and multiplication assignment operator (*=). ANS:

73 // test overloaded inequality operator74 cout << ( ( c != d ) ? " != " : " == " );75 d.printRational();76 cout << " according to the overloaded != operator" << endl;77 return 0;78 } // end main

7/3 + 1/3 = 8/37/3 - 1/3 = 27/3 * 1/3 = 7/97/3 / 1/3 = 77/3 is: > 1/3 according to the overloaded > operator >= 1/3 according to the overloaded < operator >= 1/3 according to the overloaded >= operator > 1/3 according to the overloaded <= operator != 1/3 according to the overloaded == operator != 1/3 according to the overloaded != operator

1 // Exercise 11.17 Solution: Polynomial.h2 // Polynomial class definition.3 #ifndef POLYNOMIAL_H4 #define POLYNOMIAL_H56 class Polynomial7 {8 public:9 Polynomial();

10 Polynomial operator+( const Polynomial& ) const; // addition11 Polynomial operator-( const Polynomial& ) const; // subtraction12 Polynomial operator*( const Polynomial& ); // multiplication13 const Polynomial operator=( const Polynomial& ); // assignment14 Polynomial& operator+=( const Polynomial& );15 Polynomial& operator-=( const Polynomial& );16 Polynomial& operator*=( const Polynomial& );

cpphtp5_11_IM.fm Page 606 Thursday, December 23, 2004 4:15 PM

Page 37: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 607

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

17 void enterTerms();18 void printPolynomial() const;19 int getNumberOfTerms(); // user should only be able to retrieve value20 int getTermExponent( int );21 int getTermCoefficient( int );22 void setCoefficient( int, int ); // set coefficient of a specific term23 ~Polynomial(); // destructor24 private:25 int numberOfTerms;26 int exponents[ 100 ]; // exponent array27 int coefficients[ 100 ]; // coefficients array28 void polynomialCombine( Polynomial& ); // combine common terms29 }; // end class Polynomial3031 #endif

1 // Exercise 11.17 Solution: Polynomial.cpp2 // Polynomial member-function definitions.3 #include <iostream> 4 using std::cin; 5 using std::cout; 6 using std::endl; 78 #include <iomanip> 9 using std::showpos;

10 using std::noshowpos; 1112 #include "Polynomial.h"1314 Polynomial::Polynomial()15 {16 for ( int t = 0; t < 100; t++ )17 {18 coefficients[ t ] = 0;19 exponents[ t ] = 0;20 } // end for2122 numberOfTerms = 0;23 } // end Polynomial constructor2425 void Polynomial::printPolynomial() const26 {27 int start;28 bool zero = false;2930 if ( coefficients[ 0 ] ) // output constants31 {32 cout << coefficients[ 0 ];33 start = 1;34 zero = true; // at least one term exists35 }36 else37 {38 if ( coefficients[ 1 ] )

cpphtp5_11_IM.fm Page 607 Thursday, December 23, 2004 4:15 PM

Page 38: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

608 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

39 {40 cout << coefficients[ 1 ] << 'x'; // constant does not exist41 // so output first term42 // without a sign43 if ( ( exponents[ 1 ] != 0 ) && ( exponents[ 1 ] != 1 ) )44 cout << '^' << exponents[ 1 ];4546 zero = true; // at least one term exists47 } // end inner if48 49 start = 2;50 } // end else5152 // output remaining polynomial terms53 for ( int x = start; x < 100; x++ )54 {55 if ( coefficients[ x ] != 0 )56 {57 cout << showpos << coefficients[ x ] << noshowpos << 'x'; 5859 if ( ( exponents[ x ] != 0 ) && ( exponents[ x ] != 1 ) )60 cout << '^' << exponents[ x ];6162 zero = true; // at least one term exists63 } // end if64 } // end for6566 if ( !zero ) // no terms exist in the polynomial67 cout << '0';6869 cout << endl;70 } // end function printPolynomial7172 const Polynomial Polynomial::operator=( const Polynomial& r )73 {74 exponents[ 0 ] = r.exponents[ 0 ];75 coefficients[ 0 ] = r.coefficients[ 0 ];7677 for ( int s = 1; ( s < 100 ); s++ )78 {79 if ( r.exponents[ s ] != 0 )80 {81 exponents[ s ] = r.exponents[ s ];82 coefficients[ s ] = r.coefficients[ s ];83 }84 else85 {86 if ( exponents[ s ] == 0 )87 break;8889 exponents[ s ] = 0;90 coefficients[ s ] = 0;91 } // end else92 } // end for93

cpphtp5_11_IM.fm Page 608 Thursday, December 23, 2004 4:15 PM

Page 39: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 609

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

94 return *this;95 } // end function operator=9697 Polynomial Polynomial::operator+( const Polynomial& r ) const98 {99 Polynomial temp;100 bool exponentExists;101 int s;102103 // process element with a zero exponent104 temp.coefficients[ 0 ] = coefficients[ 0 ] + r.coefficients[ 0 ];105106 // copy right arrays into temp object s will be used to keep107 // track of first open coefficient element108 for ( s = 1; ( s < 100 ) && ( r.exponents[ s ] != 0 ); s++ )109 {110 temp.coefficients[ s ] = r.coefficients[ s ];111 temp.exponents[ s ] = r.exponents[ s ];112 } // end for113114 for ( int x = 1; x < 100; x++ )115 {116 exponentExists = false; // assume exponent will not be found117118 for ( int t = 1; ( t < 100 ) && ( !exponentExists ); t++ )119120 if ( exponents[ x ] == temp.exponents[ t ] )121 {122 temp.coefficients[ t ] += coefficients[ x ];123 exponentExists = true; // exponent found124 } // end if125126 // exponent was not found, insert into temp127 if ( !exponentExists )128 {129 temp.exponents[ s ] = exponents[ x ];130 temp.coefficients[ s ] += coefficients[ x ];131 s++;132 } // end if133 } // end for134135 return temp;136 } // end function operator+137138 Polynomial &Polynomial::operator+=( const Polynomial &r )139 {140 *this = *this + r;141 return *this;142 } // end function operator+=143144 Polynomial Polynomial::operator-( const Polynomial& r ) const145 {146 Polynomial temp;147 bool exponentExists;148 int s;

cpphtp5_11_IM.fm Page 609 Thursday, December 23, 2004 4:15 PM

Page 40: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

610 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

149150 // process element with a zero exponent151 temp.coefficients[ 0 ] = coefficients[ 0 ] - r.coefficients[ 0 ];152153 // copy left arrays into temp object s will be used to keep154 // track of first open coefficient element155 for ( s = 1; ( s < 100 ) && ( exponents[ s ] != 0 ); s++ )156 {157 temp.coefficients[ s ] = coefficients[ s ];158 temp.exponents[ s ] = exponents[ s ];159 } // end for160161 for ( int x = 1; x < 100; x++ )162 {163 exponentExists = false; // assume exponent will not be found164165 for ( int t = 1; ( t < 100 ) && ( !exponentExists ); t++ )166167 if ( r.exponents[ x ] == temp.exponents[ t ] )168 {169 temp.coefficients[ t ] -= r.coefficients[ x ];170 exponentExists = true; // exponent found171 } // end if172173 // exponent was not found, insert into temp174 if ( !exponentExists )175 {176 temp.exponents[ s ] = r.exponents[ x ];177 temp.coefficients[ s ] -= r.coefficients[ x ];178 s++;179 } // end if180 } // end for181182 return temp;183 } // end function operator-184185 Polynomial &Polynomial::operator-=( const Polynomial& r )186 {187 *this = *this - r;188 return *this;189 } // end function operator-=190191 Polynomial Polynomial::operator*( const Polynomial& r )192 {193 Polynomial temp;194 int s = 1; // subscript location for temp coefficient and exponent195196 for ( int x = 0; ( x < 100 ) && 197 ( x == 0 || coefficients[ x ] != 0 ); x++ )198199 for ( int y = 0; ( y < 100 ) && 200 ( y == 0 || r.coefficients[ y ] != 0 ); y++ )201202 if ( coefficients[ x ] * r.coefficients[ y ] )203

cpphtp5_11_IM.fm Page 610 Thursday, December 23, 2004 4:15 PM

Page 41: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 611

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

204 if ( ( exponents[ x ] == 0 ) && ( r.exponents[ y ] == 0 ) )205 temp.coefficients[ 0 ] += 206 coefficients[ x ] * r.coefficients[ y ];207 else208 {209 temp.coefficients[ s ] = 210 coefficients[ x ] * r.coefficients[ y ];211 temp.exponents[ s ] = exponents[ x ] + r.exponents[ y ];212 s++;213 } // end else214215 polynomialCombine( temp ); // combine common terms216 return temp;217 } // end function operator* 218219 void Polynomial::polynomialCombine( Polynomial& w )220 {221 Polynomial temp = w;222 int exp;223224 // zero out elements of w225 for ( int x = 0; x < 100; x++ )226 {227 w.coefficients[ x ] = 0;228 w.exponents[ x ] = 0;229 } // end for230231 for ( int x = 1; x < 100; x++ )232 {233 exp = temp.exponents[ x ];234235 for ( int y = x + 1; y < 100; y++ )236237 if ( exp == temp.exponents[ y ] )238 {239 temp.coefficients[ x ] += temp.coefficients[ y ];240 temp.exponents[ y ] = 0;241 temp.coefficients[ y ] = 0;242 } // end if243 } // end outer for244245 w = temp;246 } // end function polynomialCombine247248 Polynomial &Polynomial::operator*=( const Polynomial& r )249 {250 *this = *this * r;251 return *this;252 } // end function operator*=253254 void Polynomial::enterTerms()255 {256 bool found = false; 257 int c, e, term;258

cpphtp5_11_IM.fm Page 611 Thursday, December 23, 2004 4:15 PM

Page 42: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

612 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

259 cout << "\nEnter number of polynomial terms: ";260 cin >> numberOfTerms;261262 for ( int n = 1; n <= numberOfTerms; n++ )263 {264 cout << "\nEnter coefficient: ";265 cin >> c;266 cout << "Enter exponent: ";267 cin >> e;268269 if ( c != 0 )270 {271 // exponents of zero are forced into first element272 if ( e == 0 )273 {274 coefficients[ 0 ] += c;275 continue;276 } // end if277278 for ( term = 1; ( term < 100 ) && 279 ( coefficients[ term ] != 0 ); term++ )280281 if ( e == exponents[ term ] )282 {283 coefficients[ term ] += c;284 exponents[ term ] = e;285 found = true; // existing exponent updated286 } // end if287288 if ( !found ) // add term289 {290 coefficients[ term ] += c;291 exponents[ term ] = e;292 } // end if293 } // end outer if294 } // end outer for295 } // end function endTerms296297 int Polynomial::getNumberOfTerms()298 {299 return numberOfTerms;300 } // end function getNumberOfTerms301302 int Polynomial::getTermExponent( int term )303 {304 return exponents[ term ];305 } // end function getTermExponent306307 int Polynomial::getTermCoefficient( int term )308 {309 return coefficients[ term ];310 } // end function getTermsCoefficient311312 void Polynomial::setCoefficient( int term, int coefficient )313 {

cpphtp5_11_IM.fm Page 612 Thursday, December 23, 2004 4:15 PM

Page 43: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 613

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

314 if ( coefficients[ term ] == 0 ) // no term at this location315 cout << "No term at this location, cannot set term." << endl;316 else // otherwise, set term317 coefficients[ term ] = coefficient;318 } // end function setTerm319320 // destructor321 Polynomial::~Polynomial()322 {323 // empty destructor324 } // end destructor

1 // Exercise 11.17 Solution: ex11_17.cpp2 // Polynomial test program.3 #include <iostream> 4 using std::cout; 5 using std::endl;67 #include "Polynomial.h"89 int main()

10 {11 Polynomial a, b, c, t;1213 a.enterTerms();14 b.enterTerms();15 t = a; // save the value of a16 cout << "First polynomial is:\n";17 a.printPolynomial();18 cout << "Second polynomial is:\n";19 b.printPolynomial();20 cout << "\nAdding the polynomials yields:\n";21 c = a + b;22 c.printPolynomial();23 cout << "\n+= the polynomials yields:\n";24 a += b;25 a.printPolynomial();26 cout << "\nSubtracting the polynomials yields:\n";27 a = t; // reset a to original value28 c = a - b;29 c.printPolynomial();30 cout << "\n-= the polynomials yields:\n";31 a -= b;32 a.printPolynomial();33 cout << "\nMultiplying the polynomials yields:\n";34 a = t; // reset a to original value35 c = a * b;36 c.printPolynomial();37 cout << "\n*= the polynomials yields:\n";38 a *= b;39 a.printPolynomial();40 cout << endl;41 return 0;

cpphtp5_11_IM.fm Page 613 Thursday, December 23, 2004 4:15 PM

Page 44: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

614 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

11.18 In the program of Figs. 11.3–11.5, Fig. 11.4 contains the comment “overloaded streaminsertion operator; cannot be a member function if we would like to invoke it with cout <<somePhoneNumber;.” Actually, the stream insertion operator could be a PhoneNumber class memberfunction if we were willing to invoke it either as somePhoneNumber.operator<<( cout ); or as some-PhoneNumber << cout;. Rewrite the program of Fig. 11.5 with the overloaded stream insertion op-erator<< as a member function and try the two preceding statements in the program to demonstratethat they work.

ANS:

42 } // end main

Enter number of polynomial terms: 2

Enter coefficient: 2Enter exponent: 2

Enter coefficient: 3Enter exponent: 3

Enter number of polynomial terms: 3

Enter coefficient: 1Enter exponent: 1

Enter coefficient: 2Enter exponent: 2

Enter coefficient: 3Enter exponent: 3First polynomial is:2x^2+3x^3Second polynomial is:1x+2x^2+3x^3

Adding the polynomials yields:1x+4x^2+6x^3

+= the polynomials yields:1x+4x^2+6x^3

Subtracting the polynomials yields:-1x

-= the polynomials yields:-1x

Multiplying the polynomials yields:2x^3+7x^4+12x^5+9x^6

*= the polynomials yields:2x^3+7x^4+12x^5+9x^6

1 // Exercise 11.18 Solution: PhoneNumber.h

cpphtp5_11_IM.fm Page 614 Thursday, December 23, 2004 4:15 PM

Page 45: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

Solutions 615

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

2 // PhoneNumber class definition3 #ifndef PHONENUMBER_H4 #define PHONENUMBER_H56 #include <iostream>7 using std::ostream;8 using std::istream;9

10 #include <string>11 using std::string;1213 class PhoneNumber14 {15 friend istream &operator>>( istream &, PhoneNumber & );16 public:17 ostream &operator<<( ostream &output );18 private:19 string areaCode; // 3-digit area code 20 string exchange; // 3-digit exchange 21 string line; // 4-digit line 22 }; // end class PhoneNumber2324 #endif

1 // Exercise 11.18 Solution: PhoneNumber.cpp2 // Overloaded stream insertion and stream extraction operators3 // for class PhoneNumber.4 #include <iomanip>5 using std::setw;67 #include "PhoneNumber.h"89 // overloaded stream insertion operator; cannot be

10 // a member function if we would like to invoke it with11 // cout << somePhoneNumber;12 ostream &PhoneNumber::operator<<( ostream &output )13 {14 output << "(" << areaCode << ") " << exchange << "-" << line;15 return output; // enables cout << a << b << c;16 } // end function operator<<1718 // overloaded stream extraction operator; cannot be19 // a member function if we would like to invoke it with20 // cin >> somePhoneNumber;21 istream &operator>>( istream &input, PhoneNumber &number )22 {23 input.ignore(); // skip (24 input >> setw( 3 ) >> number.areaCode; // input area code25 input.ignore( 2 ); // skip ) and space26 input >> setw( 3 ) >> number.exchange; // input exchange 27 input.ignore(); // skip dash (-)28 input >> setw( 4 ) >> number.line; // input line

cpphtp5_11_IM.fm Page 615 Thursday, December 23, 2004 4:15 PM

Page 46: Operator Overloading; Array Objects · ANS: For operator overloading: It would be the name of a function that would provide an overloaded version of the / operator for a specific

616 Chapter 11 Operator Overloading; String and Array Objects

Copyright ® 1992-2005 by Deitel & Associates, Inc. All Rights Reserved

29 return input; // enables cin >> a >> b >> c;30 } // end function operator>>

1 // Exercise 11.18 Solution: ex11_18.cpp2 // Demonstrating class PhoneNumber's overloaded stream insertion 3 // and stream extraction operators.4 #include <iostream>5 using std::cout;6 using std::cin;7 using std::endl;89 #include "PhoneNumber.h"

1011 int main()12 {13 PhoneNumber phone; // create object phone1415 cout << "Enter phone number in the form (123) 456-7890:" << endl;1617 // cin >> phone invokes operator>> by implicitly issuing18 // the global function call operator>>( cin, phone ) 19 cin >> phone; 2021 cout << "The phone number entered was: ";2223 // cout << phone invokes operator<< by implicitly issuing 24 // the global function call operator<<( cout, phone )25 phone.operator << ( cout ) << endl;26 return 0;27 } // end main

Enter phone number in the form (123) 456-7890:(800) 555-1212The phone number entered was: (800) 555-1212

cpphtp5_11_IM.fm Page 616 Thursday, December 23, 2004 4:15 PM