Sunteți pe pagina 1din 37

Chapter 1

Answers to Questions

1. procedural, object-oriented

2. b

3. data, act on that data

4. a

5. data hiding

6. a, d

7. objects

8. false; the organizational principles are different

9. encapsulation

10. d

11. false; most lines of code are the same in C and C++

12. polymorphism

13. d

14. b

15. b, d

Chapter 2

Answers to Questions

1. b, c

2. parentheses

3. braces { }

4. It’s the first function executed when the program starts


5. statement

6. // this is a comment
/* this is a comment */

7. a, d

8. a. 4

b. 10

c. 4

d. 4

9. false

10. a. integer constant

b. character constant

c. floating-point constant

d. variable name or identifier

e. function name

11. a. cout << 'x';

b. cout << "Jim";

c. cout << 509;

12. false; they’re not equal until the statement is executed

13. cout << setw(10) << george;

14. IOSTREAM

15. cin >> temp;

16. IOMANIP

17. string constants, preprocessor directives

18. true
19. 2

20. assignment (=) and arithmetic (like + and *)

21. temp += 23;


temp = temp + 23;

22. 1

23. 2020

24. to provide declarations and other data for library functions, overloaded operators, and objects

25. library

Solutions to Exercises

1. // ex2_1.cpp
// converts gallons to cubic feet
#include <iostream>
using namespace std;

int main()
{
float gallons, cufeet;

cout << "\nEnter quantity in gallons: ";


cin >> gallons;
cufeet = gallons / 7.481;
cout << "Equivalent in cublic feet is " << cufeet << endl;
return 0;
}

2. // ex2_2.cpp
// generates table
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
cout << 1990 << setw(8) << 135 << endl
<< 1991 << setw(8) << 7290 << endl
<< 1992 << setw(8) << 11300 << endl
<< 1993 << setw(8) << 16200 << endl;
return 0;
}

3. // ex2_3.cpp
// exercises arithmetic assignment and decrement
#include <iostream>
using namespace std;

int main()
{
int var = 10;

cout << var << endl; // var is 10


var *= 2; // var becomes 20
cout << var-- << endl; // displays var, then decrements it
cout << var << endl; // var is 19
return 0;
}

Chapter 3

Answers to Questions

1. b, c

2. george != sally

3. −1 is true; only 0 is false.

4. The initialize expression initializes the loop variable, the test expression tests the loop
variable, and the increment expression changes the loop variable.

5. c, d

6. true

7. for(int j=100; j<=110; j++)


cout << endl << j;

8. braces (curly brackets)

9. c

10. int j = 100;


while( j <= 110 )
cout << endl << j++;
11. false

12. at least once

13. int j = 100;


do
cout << endl << j++;
while( j <= 110 );

14. if(age > 21)


cout << "Yes";

15. d

16. if( age > 21 )


cout << "Yes";
else
cout << "No";

17. a, c

18. '\r'

19. preceding, surrounded by braces

20. reformatting

21. switch(ch)
{
case 'y':
cout << "Yes";
break;
case 'n':
cout << "No";
break;
default:
cout << "Unknown response";
}

22. ticket = (speed > 55) ? 1 : 0;

23. d

24. limit == 55 && speed > 55

25. unary, arithmetic, relational, logical, conditional, assignment


26. d

27. the top of the loop

28. b

Solutions to Exercises

1. // ex3_1.cpp
// displays multiples of a number
#include <iostream>
#include <iomanip> //for setw()
using namespace std;

int main()
{

unsigned long n; //number

cout << "\nEnter a number: ";


cin >> n; //get number
for(int j=1; j<=200; j++) //loop from 1 to 200
{
cout << setw(5) << j*n << " "; //print multiple of n
if( j%10 == 0 ) //every 10 numbers,
cout << endl; //start new line
}
return 0;
}

2. // ex3_2.cpp
// converts fahrenheit to centigrad, or
// centigrad to fahrenheit
#include <iostream>
using namespace std;

int main()
{
int response;
double temper;

cout << "\nType 1 to convert fahrenheit to celsius,"


<< "\n 2 to convert celsius to fahrenheit: ";
cin >> response;
if( response == 1 )
{
cout << "Enter temperature in fahrenheit: ";
cin >> temper;
cout << "In celsius that's " << 5.0/9.0*(temper-32.0);
}
else
{
cout << "Enter temperature in celsius: ";
cin >> temper;
cout << "In fahrenheit that's " << 9.0/5.0*temper + 32.0;
}
cout << endl;
return 0;
}

3. // ex3_3.cpp
// makes a number out of digits
#include <iostream>
using namespace std;
#include <conio.h> //for getche()

int main()
{
char ch;
unsigned long total = 0; //this holds the number

cout << "\nEnter a number: ";


while( (ch=getche()) != '\r' ) //quit on Enter
total = total*10 + ch-'0'; //add digit to total*10
cout << "\nNumber is: " << total << endl;
return 0;
}

4. // ex3_4.cpp
// models four-function calculator
#include <iostream>
using namespace std;

int main()
{
double n1, n2, ans;
char oper, ch;

do {
cout << "\nEnter first number, operator, second number: ";
cin >> n1 >> oper >> n2;
switch(oper)
{
case '+': ans = n1 + n2; break;
case '-': ans = n1 - n2; break;
case '*': ans = n1 * n2; break;
case '/': ans = n1 / n2; break;
default: ans = 0;
}
cout << "Answer = " << ans;
cout << "\nDo another (Enter 'y' or 'n')? ";
cin >> ch;
} while( ch != 'n' );
return 0;
}

Chapter 4

Answers to Questions

1. b, d

2. true

3. semicolon

4. struct time
{
int hrs;
int mins;
int secs;
};

5. false; only a variable definition creates space in memory

6. c

7. time2.hrs = 11;

8. 18 in 16-bit systems (3 structures times 3 integers times 2 bytes), or 36 in 32-bit systems

9. time time1 = { 11, 10, 59 };

10. true

11. temp = fido.dogs.paw;

12. c
13. enum players { B1, B2, SS, B3, RF, CF, LF, P, C };

14. players joe, tom;


joe = LF;
tom = P;

15. a. no

b. yes

c. no

d. yes

16. 0, 1, 2

17. enum speeds { obsolete=78, single=45, album=33 };

18. because false should be represented by 0

Solutions to Exercises

1. // ex4_1.cpp
// uses structure to store phone number
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct phone
{
int area; //area code (3 digits)
int exchange; //exchange (3 digits)
int number; //number (4 digits)
};
////////////////////////////////////////////////////////////////
int main()
{
phone ph1 = { 212, 767, 8900 }; //initialize phone number
phone ph2; //define phone number
// get phone no from user
cout << "\nEnter your area code, exchange, and number";
cout << "\n(Don't use leading zeros): ";
cin >> ph2.area >> ph2.exchange >> ph2.number;

cout << "\nMy number is " //display numbers


<< '(' << ph1.area << ") "
<< ph1.exchange << '-' << ph1.number;
cout << "\nYour number is "
<< '(' << ph2.area << ") "
<< ph2.exchange << '-' << ph2.number << endl;
return 0;
}

2. // ex4_2.cpp
// structure models point on the plane
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct point
{
int xCo; //X coordinate
int yCo; //Y coordinate
};
////////////////////////////////////////////////////////////////

int main()
{
point p1, p2, p3; //define 3 points

cout << "\nEnter coordinates for p1: "; //get 2 points


cin >> p1.xCo >> p1.yCo; //from user
cout << "Enter coordinates for p2: ";
cin >> p2.xCo >> p2.yCo;

p3.xCo = p1.xCo + p2.xCo; //find sum of


p3.yCo = p1.yCo + p2.yCo; //p1 and p2

cout << "Coordinates of p1+p2 are: " //display the sum


<< p3.xCo << ", " << p3.yCo << endl;
return 0;
}

3. // ex4_3.cpp
// uses structure to model volume of room
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct Distance
{
int feet;
float inches;
};
////////////////////////////////////////////////////////////////
struct Volume
{
Distance length;
Distance width;
Distance height;
};
////////////////////////////////////////////////////////////////
int main()
{
float l, w, h;
Volume room1 = { { 16, 3.5 }, { 12, 6.25 }, { 8, 1.75 } };

l = room1.length.feet + room1.length.inches/12.0;
w = room1.width.feet + room1.width.inches /12.0;
h = room1.height.feet + room1.height.inches/12.0;

cout << "Volume = " << l*w*h << " cubic feet\n";
return 0;
}

Chapter 5

Answers to Questions

1. d (half credit for b)

2. definition

3. void foo()
{
cout << "foo";
}

4. declaration, prototype

5. body

6. call

7. declarator

8. c

9. false
10. To clarify the purpose of the arguments

11. a, b, c

12. Empty parentheses mean the function takes no arguments

13. one

14. Ttrue

15. at the beginning of the declaration and declarator

16. void

17. main()
{
int times2(int); // prototype
int alpha = times2(37); // function call
}

18. d

19. to modify the original argument (or to avoid copying a large argument)

20. a, c

21. int bar(char);


int bar(char, char);

22. faster, more

23. inline float foobar(float fvar)

24. a, b

25. char blyth(int, float=3.14159);

26. visibility, lifetime

27. those functions defined following the variable definition

28. the function in which it is defined

29. b, d

30. on the left side of the equal sign


Solutions to Exercises

1. // ex5_1.cpp
// function finds area of circle
#include <iostream>
using namespace std;
float circarea(float radius);

int main()
{
double rad;
cout << "\nEnter radius of circle: ";
cin >> rad;
cout << "Area is " << circarea(rad) << endl;
return 0;
}
//--------------------------------------------------------------
float circarea(float r)
{
const float PI = 3.14159F;
return r * r * PI;
}

2. // ex5_2.cpp
// function raises number to a power
#include <iostream>
using namespace std;
double power( double n, int p=2); //p has default value 2

int main()
{
double number, answer;
int pow;
char yeserno;

cout << "\nEnter number: "; //get number


cin >> number;
cout << "Want to enter a power (y/n)? ";
cin >> yeserno;
if( yeserno == 'y' ) //user wants a non-2 power?
{
cout << "Enter power: ";
cin >> pow;
answer = power(number, pow); //raise number to pow
}
else
answer = power(number); //square the number
cout << "Answer is " << answer << endl;
return 0;
}
//--------------------------------------------------------------
// power()
// returns number n raised to a power p
double power( double n, int p )
{
double result = 1.0; //start with 1
for(int j=0; j<p; j++) //multiply by n
result *= n; //p times
return result;
}

3. // ex5_3.cpp
// function sets smaller of two numbers to 0
#include <iostream>
using namespace std;

int main()
{
void zeroSmaller(int&, int&);
int a=4, b=7, c=11, d=9;

zeroSmaller(a, b);
zeroSmaller(c, d);

cout << "\na=" << a << " b=" << b


<< " c=" << c << " d=" << d;
return 0;
}
//--------------------------------------------------------------
// zeroSmaller()
// sets the smaller of two numbers to 0
void zeroSmaller(int& first, int& second)
{
if( first < second )
first = 0;
else
second = 0;
}

4. // ex5_4.cpp
// function returns larger of two distances
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
struct Distance // English distance
{
int feet;
float inches;
};
////////////////////////////////////////////////////////////////
Distance bigengl(Distance, Distance); //declarations
void engldisp(Distance);

int main()
{
Distance d1, d2, d3; //define three lengths
//get length d1 from user
cout << "\nEnter feet: "; cin >> d1.feet;
cout << "Enter inches: "; cin >> d1.inches;
//get length d2 from user
cout << "\nEnter feet: "; cin >> d2.feet;
cout << "Enter inches: "; cin >> d2.inches;

d3 = bigengl(d1, d2); //d3 is larger of d1 and d2


//display all lengths
cout << "\nd1="; engldisp(d1);
cout << "\nd2="; engldisp(d2);
cout << "\nlargest is "; engldisp(d3); cout << endl;
return 0;
}

//--------------------------------------------------------------
// bigengl()
// compares two structures of type Distance, returns the larger
Distance bigengl( Distance dd1, Distance dd2 )
{
if(dd1.feet > dd2.feet) //if feet are different, return
return dd1; //the one with the largest feet
if(dd1.feet < dd2.feet)
return dd2;
if(dd1.inches > dd2.inches) //if inches are different,
return dd1; //return one with largest
else //inches, or dd2 if equal
return dd2;
}
//--------------------------------------------------------------
// engldisp()
// display structure of type Distance in feet and inches
void engldisp( Distance dd )
{
cout << dd.feet << "\'-" << dd.inches << "\"";
}

Chapter 6

Answers to Questions

1. A class declaration describes how objects of a class will look when they are created.

2. class, object

3. c

4. class leverage
{
private:
int crowbar;
public:
void pry();
};

5. false; both data and functions can be private or public

6. leverage lever1;

7. d

8. lever1.pry();

9. inline (also private)

10. int getcrow()


{ return crowbar; }

11. created (defined)

12. the class of which it is a member

13. leverage()
{ crowbar = 0; }

14. true

15. a
16. int getcrow();

17. int leverage::getcrow()


{ return crowbar; }

18. member functions and data are, by default, public in structures but private in classes

19. three, one

20. calling one of its member functions

21. b, c, d

22. false; trial and error may be necessary

23. d

24. true

25. void aFunc(const float jerry) const;

Solutions to Exercises

1. // ex6_1.cpp
// uses a class to model an integer data type
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Int //(not the same as int)
{
private:
int i;
public:
Int() //create an Int
{ i = 0; }

Int(int ii) //create and initialize an Int


{ i = ii; }
void add(Int i2, Int i3) //add two Ints
{ i = i2.i + i3.i; }
void display() //display an Int
{ cout << i; }
};
////////////////////////////////////////////////////////////////
int main()
{
Int Int1(7); //create and initialize an Int
Int Int2(11); //create and initialize an Int
Int Int3; //create an Int

Int3.add(Int1, Int2); //add two Ints


cout << "\nInt3 = "; Int3.display(); //display result
cout << endl;
return 0;
}

2. // ex6_2.cpp
// uses class to model toll booth
#include <iostream>
using namespace std;
#include <conio.h>

const char ESC = 27; //escape key ASCII code


const double TOLL = 0.5; //toll is 50 cents
////////////////////////////////////////////////////////////////
class tollBooth
{
private:
unsigned int totalCars; //total cars passed today
double totalCash; //total money collected today
public: //constructor
tollBooth() : totalCars(0), totalCash(0.0)
{ }
void payingCar() //a car paid
{ totalCars++; totalCash += TOLL; }
void nopayCar() //a car didn't pay
{ totalCars++; }
void display() const //display totals
{ cout << "\nCars=" << totalCars
<< ", cash=" << totalCash
<< endl; }
};

////////////////////////////////////////////////////////////////
int main()
{
tollBooth booth1; //create a toll booth
char ch;

cout << "\nPress 0 for each non-paying car,"


<< "\n 1 for each paying car,"
<< "\n Esc to exit the program.\n";
do {
ch = getche(); //get character
if( ch == '0' ) //if it's 0, car didn't pay
booth1.nopayCar();
if( ch == '1' ) //if it's 1, car paid
booth1.payingCar();
} while( ch != ESC ); //exit loop on Esc key
booth1.display(); //display totals
return 0;
}

3. // ex6_3.cpp
// uses class to model a time data type
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class time
{
private:
int hrs, mins, secs;
public:
time() : hrs(0), mins(0), secs(0) //no-arg constructor
{ }
//3-arg constructor
time(int h, int m, int s) : hrs(h), mins(m), secs(s)
{ }

void display() const //format 11:59:59


{ cout << hrs << ":" << mins << ":" << secs; }

void add_time(time t1, time t2) //add two times


{
secs = t1.secs + t2.secs; //add seconds
if( secs > 59 ) //if overflow,
{ secs -= 60; mins++; } // carry a minute
mins += t1.mins + t2.mins; //add minutes

if( mins > 59 ) //if overflow,


{ mins -= 60; hrs++; } // carry an hour
hrs += t1.hrs + t2.hrs; //add hours
}
};
////////////////////////////////////////////////////////////////
int main()
{
const time time1(5, 59, 59); //creates and initialze
const time time2(4, 30, 30); // two times
time time3; //create another time

time3.add_time(time1, time2); //add two times


cout << "time3 = "; time3.display(); //display result
cout << endl;
return 0;
}

Chapter 7

Answers to Questions

1. d

2. same

3. double doubleArray[100];

4. 0, 9

5. cout << doubleArray[j];

6. c

7. int coins[] = { 1, 5, 10, 25, 50, 100 };

8. d

9. twoD[2][4]

10. true

11. float flarr[3][3] = { {52,27,83}, {94,73,49}, {3,6,1} };

12. memory address

13. a, d

14. an array with 1000 elements of structure or class employee

15. emplist[16].salary

16. d

17. bird manybirds[50];


18. false

19. manybirds[26].cheep();

20. array, char

21. char city[21] (An extra byte is needed for the null character.)

22. char dextrose[] = "C6H12O6-H2O";

23. true

24. d

25. strcpy(blank, name);

26. class dog


{
private:
char breed[80];
int age;
};

27. false

28. b, c

29. int n = s1.find("cat");

30. s1.insert(12, "cat");

Solutions to Exercises

1. // ex7_1.cpp
// reverses a C-string
#include <iostream>
#include <cstring> //for strlen()
using namespace std;

int main()
{
void reversit( char[] ); //prototype
const int MAX = 80; //array size
char str[MAX]; //string

cout << "\nEnter a string: "; //get string from user


cin.get(str, MAX);

reversit(str); //reverse the string

cout << "Reversed string is: "; //display it


cout << str << endl;
return 0;
}
//--------------------------------------------------------------
//reversit()
//function to reverse a string passed to it as an argument
void reversit( char s[] )
{
int len = strlen(s); //find length of string
for(int j = 0; j < len/2; j++) //swap each character
{ // in first half
char temp = s[j]; // with character
s[j] = s[len-j-1]; // in second half
s[len-j-1] = temp;
}
}

// reversit()
// function to reverse a string passed to it as an argument
void reversit( char s[] )
{
int len = strlen(s); // find length of string
for(int j = 0; j < len/2; j++) // swap each character
{ // in first half
char temp = s[j]; // with character
s[j] = s[len-j-1]; // in second half
s[len-j-1] = temp;
}
}

2. // ex7_2.cpp
// employee object uses a string as data
#include <iostream>
#include <string>
using namespace std;
////////////////////////////////////////////////////////////////
class employee
{
private:
string name;
long number;
public:
void getdata() //get data from user
{
cout << "\nEnter name: "; cin >> name;
cout << "Enter number: "; cin >> number;
}
void putdata() //display data
{
cout << "\n Name: " << name;
cout << "\n Number: " << number;
}
};
////////////////////////////////////////////////////////////////
int main()
{
employee emparr[100]; //an array of employees
int n = 0; //how many employees
char ch; //user response

do { //get data from user


cout << "\nEnter data for employee number " << n+1;
emparr[n++].getdata();
cout << "Enter another (y/n)? "; cin >> ch;
} while( ch != 'n' );

for(int j=0; j<n; j++) //display data in array


{
cout << "\nEmployee number " << j+1;
emparr[j].putdata();
}
cout << endl;
return 0;
}

3. // ex7_3.cpp
// averages an array of Distance objects input by user
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance // English Distance class
{
private:
int feet;
float inches;
public:
Distance() //constructor (no args)
{ feet = 0; inches = 0; }
Distance(int ft, float in) //constructor (two args)
{ feet = ft; inches = in; }

void getdist() //get length from user


{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}

void showdist() //display distance


{ cout << feet << "\'-" << inches << '\"'; }

void add_dist( Distance, Distance ); //declarations


void div_dist( Distance, int );
};
//--------------------------------------------------------------
//add Distances d2 and d3
void Distance::add_dist(Distance d2, Distance d3)
{
inches = d2.inches + d3.inches; //add the inches
feet = 0; //(for possible carry)
if(inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet
} //by 1
feet += d2.feet + d3.feet; //add the feet
}
//--------------------------------------------------------------
//divide Distance by int
void Distance::div_dist(Distance d2, int divisor)
{
float fltfeet = d2.feet + d2.inches/12.0; //convert to float
fltfeet /= divisor; //do division
feet = int(fltfeet); //get feet part
inches = (fltfeet-feet) * 12.0; //get inches part
}
////////////////////////////////////////////////////////////////
int main()
{
Distance distarr[100]; //array of 100 Distances
Distance total(0, 0.0), average; //other Distances
int count = 0; //counts Distances input
char ch; //user response character

do {
cout << "\nEnter a Distance"; //get Distances
distarr[count++].getdist(); //from user, put
cout << "\nDo another (y/n)? "; //in array
cin >> ch;
}while( ch != 'n' );

for(int j=0; j<count; j++) //add all Distances


total.add_dist( total, distarr[j] ); //to total
average.div_dist( total, count ); //divide by number

cout << "\nThe average is: "; //display average


average.showdist();
cout << endl;
return 0;
}

Chapter 8

Answers to Questions

1. a, c

2. x3.subtract(x2, x1);

3. x3 = x2 - x1;

4. true

5. void operator -- () { count--; }

6. none

7. b, d

8. void Distance::operator ++ ()
{
++feet;
}

9. Distance Distance::operator ++ ()
{
int f = ++feet;
float i = inches;
return Distance(f, i);
}

10. It increments the variable prior to use, the same as a non-overloaded ++operator.

11. c, e, b, a, d

12. true

13. b, c

14. String String::operator ++ ()


{
int len = strlen(str);
for(int j=0; j<len; j++)
str[j] = toupper( str[j] )
return String(str);
}

15. d

16. false if there is a conversion routine; true otherwise

17. b

18. true

19. constructor

20. true, but it will be hard for humans to understand

21. d

22. attributes, operations

23. false

24. a

Solutions to Exercises

1. // ex8_1.cpp
// overloaded '-' operator subtracts two Distances
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ } //constructor (two args)

Distance(int ft, float in) : feet(ft), inches(in)


{ }
void getdist() //get length from user
{
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() //display distance
{ cout << feet << "\'-" << inches << '\"'; }

Distance operator + ( Distance ); //add two distances


Distance operator - ( Distance ); //subtract two distances
};
//--------------------------------------------------------------
//add d2 to this distance
Distance Distance::operator + (Distance d2) //return the sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
i -= 12.0; //by 12.0 and
f++; //increase feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to sum
}
//--------------------------------------------------------------
//subtract d2 from this dist
Distance Distance::operator - (Distance d2) //return the diff
{
int f = feet - d2.feet; //subtract the feet
float i = inches - d2.inches; //subtract the inches
if(i < 0) //if inches less than 0,
{ //then increase inches
i += 12.0; //by 12.0 and
f--; //decrease feet by 1
} //return a temporary Distance
return Distance(f,i); //initialized to difference
}
////////////////////////////////////////////////////////////////
int main()
{
Distance dist1, dist3; //define distances
dist1.getdist(); //get dist1 from user

Distance dist2(3, 6.25); //define, initialize dist2

dist3 = dist1 - dist2; //subtract

//display all lengths


cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
cout << "\ndist3 = "; dist3.showdist();
cout << endl;
return 0;
}

2. // ex8_2.cpp
// overloaded '+=' operator concatenates strings
#include <iostream>
#include <cstring> //for strcpy(), strlen()
using namespace std;
#include <process.h> //for exit()
////////////////////////////////////////////////////////////////
class String //user-defined string type
{
private:
enum { SZ = 80 }; //size of String objects
char str[SZ]; //holds a C-string
public:
String() //no-arg constructor
{ strcpy(str, ""); }
String( char s[] ) //1-arg constructor
{ strcpy(str, s); }
void display() //display the String
{ cout << str; }
String operator += (String ss) //add a String to this one
{ //result stays in this one
if( strlen(str) + strlen(ss.str) >= SZ )
{ cout << "\nString overflow"; exit(1); }
strcat(str, ss.str); //add the argument string
return String(str); //return temp String
}
};
////////////////////////////////////////////////////////////////
int main()
{
String s1 = "Merry Christmas! "; //uses 1-arg ctor
String s2 = "Happy new year!"; //uses 1-arg ctor
String s3; //uses no-arg ctor

s3 = s1 += s2; //add s2 to s1, assign to s3

cout << "\ns1="; s1.display(); //display s1


cout << "\ns2="; s2.display(); //display s2
cout << "\ns3="; s3.display(); //display s3
cout << endl;
return 0;
}

3. // ex8_3.cpp
// overloaded '+' operator adds two times
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class time
{
private:
int hrs, mins, secs;
public:
time() : hrs(0), mins(0), secs(0) //no-arg constructor
{ } //3-arg constructor
time(int h, int m, int s) : hrs(h), mins(m), secs(s)
{ }
void display() //format 11:59:59
{ cout << hrs << ":" << mins << ":" << secs; }

time operator + (time t2) //add two times


{
int s = secs + t2.secs; //add seconds
int m = mins + t2.mins; //add minutes
int h = hrs + t2.hrs; //add hours
if( s > 59 ) //if secs overflow,
{ s -= 60; m++; } // carry a minute
if( m > 59 ) //if mins overflow,
{ m -= 60; h++; } // carry an hour
return time(h, m, s); //return temp value
}
};
////////////////////////////////////////////////////////////////
int main()
{
time time1(5, 59, 59); //create and initialze
time time2(4, 30, 30); // two times
time time3; //create another time

time3 = time1 + time2; //add two times


cout << "\ntime3 = "; time3.display(); //display result
cout << endl;
return 0;
}

4. // ex8_4.cpp
// overloaded arithmetic operators work with type Int
#include <iostream>
using namespace std;
#include <process.h> //for exit()
////////////////////////////////////////////////////////////////
class Int
{
private:
int i;
public:
Int() : i(0) //no-arg constructor
{ }
Int(int ii) : i(ii) //1-arg constructor
{ } // (int to Int)
void putInt() //display Int
{ cout << i; }
void getInt() //read Int from kbd
{ cin >> i; }
operator int() //conversion operator
{ return i; } // (Int to int)
Int operator + (Int i2) //addition
{ return checkit( long double(i)+long double(i2) ); }
Int operator - (Int i2) //subtraction
{ return checkit( long double(i)-long double(i2) ); }
Int operator * (Int i2) //multiplication
{ return checkit( long double(i)*long double(i2) ); }
Int operator / (Int i2) //division
{ return checkit( long double(i)/long double(i2) ); }

Int checkit(long double answer) //check results


{
if( answer > 2147483647.0L || answer < -2147483647.0L )
{ cout << "\nOverflow Error\n"; exit(1); }
return Int( int(answer) );
}
};
////////////////////////////////////////////////////////////////
int main()
{

Int alpha = 20;


Int beta = 7;
Int delta, gamma;

gamma = alpha + beta; //27


cout << "\ngamma="; gamma.putInt();
gamma = alpha - beta; //13
cout << "\ngamma="; gamma.putInt();
gamma = alpha * beta; //140
cout << "\ngamma="; gamma.putInt();
gamma = alpha / beta; //2
cout << "\ngamma="; gamma.putInt();

delta = 2147483647;
gamma = delta + alpha; //overflow error
delta = -2147483647;
gamma = delta - alpha; //overflow error

cout << endl;


return 0;
}

Chapter 9

Answers to Questions

1. a, c

2. derived

3. b, c, d

4. class Bosworth : public Alphonso

5. false

6. protected
7. yes (assuming basefunc is not private)

8. BosworthObj.alfunc();

9. true

10. the one in the derived class

11. Bosworth() : Alphonso() { }

12. c, d

13. true

14. Derv(int arg) : Base(arg)

15. a

16. true

17. c

18. class Tire : public Wheel, public Rubber

19. Base::func();

20. false

21. generalization

22. d

23. false

24. stronger, aggregation

Solutions to Exercises

1. // ex9_1.cpp
// publication class and derived classes
#include <iostream>
#include <string>
using namespace std;
////////////////////////////////////////////////////////////////
class publication // base class
{
private:
string title;
float price;
public:
void getdata()
{
cout << "\nEnter title: "; cin >> title;
cout << "Enter price: "; cin >> price;
}
void putdata() const
{
cout << "\nTitle: " << title;
cout << "\nPrice: " << price;
}
};
////////////////////////////////////////////////////////////////
class book : private publication // derived class
{
private:
int pages;

public:
void getdata()
{
publication::getdata();
cout << "Enter number of pages: "; cin >> pages;
}
void putdata() const
{
publication::putdata();
cout << "\nPages: " << pages;
}
};
////////////////////////////////////////////////////////////////
class tape : private publication // derived class
{
private:
float time;
public:
void getdata()
{
publication::getdata();
cout << "Enter playing time: "; cin >> time;
}
void putdata() const
{
publication::putdata();
cout << "\nPlaying time: " << time;
}
};
////////////////////////////////////////////////////////////////
int main()
{
book book1; // define publications
tape tape1;

book1.getdata(); // get data for them


tape1.getdata();

book1.putdata(); // display their data


tape1.putdata();
cout << endl;
return 0;
}

2. // ex9_2.cpp
//inheritance from String class
#include <iostream>

#include <cstring> //for strcpy(), etc.


using namespace std;
////////////////////////////////////////////////////////////////
class String //base class
{
protected: //Note: can't be private
enum { SZ = 80 }; //size of all String objects
char str[SZ]; //holds a C-string
public:
String() //constructor 0, no args
{ str[0] = '\0'; }
String( char s[] ) //constructor 1, one arg
{ strcpy(str, s); } // convert string to String
void display() const //display the String
{ cout << str; }
operator char*() //conversion function
{ return str; } //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring : public String //derived class
{
public:
Pstring( char s[] ); //constructor
};
//--------------------------------------------------------------
Pstring::Pstring( char s[] ) //constructor for Pstring
{
if(strlen(s) > SZ-1) //if too long,
{
for(int j=0; j<SZ-1; j++) //copy the first SZ-1
str[j] = s[j]; //characters "by hand"
str[j] = '\0'; //add the null character
}
else //not too long,
String(s); //so construct normally
}
////////////////////////////////////////////////////////////////
int main()
{ //define String
Pstring s1 = "This is a very long string which is probably "
"no, certainly--going to exceed the limit set by SZ.";
cout << "\ns1="; s1.display(); //display String

Pstring s2 = "This is a short string."; //define String


cout << "\ns2="; s2.display(); //display String
cout << endl;
return 0;
}

3. // ex9_3.cpp
// multiple inheritance with publication class
#include <iostream>
#include <string>
using namespace std;
////////////////////////////////////////////////////////////////
class publication
{
private:
string title;
float price;
public:
void getdata()
{
cout << "\nEnter title: "; cin >> title;
cout << " Enter price: "; cin >> price;
}
void putdata() const
{
cout << "\nTitle: " << title;
cout << "\n Price: " << price;
}
};
////////////////////////////////////////////////////////////////
class sales
{
private:
enum { MONTHS = 3 };
float salesArr[MONTHS];
public:
void getdata();
void putdata() const;
};
//--------------------------------------------------------------
void sales::getdata()
{
cout << " Enter sales for 3 months\n";
for(int j=0; j<MONTHS; j++)
{
cout << " Month " << j+1 << ": ";
cin >> salesArr[j];
}
}

//--------------------------------------------------------------
void sales::putdata() const
{
for(int j=0; j<MONTHS; j++)
{
cout << "\n Sales for month " << j+1 << ": ";
cout << salesArr[j];
}
}
////////////////////////////////////////////////////////////////
class book : private publication, private sales
{
private:
int pages;
public:
void getdata()
{
publication::getdata();
cout << " Enter number of pages: "; cin >> pages;
sales::getdata();
}
void putdata() const
{
publication::putdata();
cout << "\n Pages: " << pages;
sales::putdata();
}
};
////////////////////////////////////////////////////////////////
class tape : private publication, private sales
{
private:
float time;
public:
void getdata()
{
publication::getdata();
cout << " Enter playing time: "; cin >> time;
sales::getdata();
}
void putdata() const
{
publication::putdata();
cout << "\n Playing time: " << time;
sales::putdata();
}
};

////////////////////////////////////////////////////////////////
int main()
{
book book1; // define publications
tape tape1;

book1.getdata(); // get data for publications


tape1.getdata();

book1.putdata(); // display data for publications


tape1.putdata();
cout << endl;
return 0;
}

S-ar putea să vă placă și