Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

lafore_robert_objectoriented_programming_in_c

.pdf
Скачиваний:
51
Добавлен:
27.03.2023
Размер:
8.94 Mб
Скачать

Answers to Questions and Exercises

935

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;

 

G

Q E UESTIONS ANSWERS XERCISES AND TO

936

Appendix G

 

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

 

 

Answers to Questions and Exercises

937

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);

}

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

938

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)

Answers to Questions and Exercises

939

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

G

Q E UESTIONS ANSWERS XERCISES AND TO

Distance dist2(3, 6.25);

//define, initialize dist2

Appendix G

940

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

 

 

 

 

Answers to Questions and Exercises

 

 

 

 

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

941

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

942

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()

{

Answers to Questions and Exercises

943

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)

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

944

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;