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

lafore_robert_objectoriented_programming_in_c

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

Answers to Questions and Exercises

945

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.

G

Q E UESTIONS ANSWERS XERCISES AND TO

// ex9_2.cpp

//inheritance from String class #include <iostream>

Appendix G

946

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

}

Answers to Questions and Exercises

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

}

}

947

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

948

//--------------------------------------------------------------

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

}

};

Answers to Questions and Exercises

949

////////////////////////////////////////////////////////////////

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;

 

}

 

Chapter 10

Answers to Questions

1. cout << &testvar;

2.4 bytes

3.c

4.&var, *var, var&, char*

5.constant; variable

6.float* ptrtofloat;

7.name

8.*testptr

9.pointer to; contents of the variable pointed to by

10.b, c, d

11.No. The address &intvar must be placed in the pointer intptr before it can be accessed.

12.any data type

13.They both do the same thing.

14.

for(int j=0; j<77; j++)

cout << endl << *(intarr+j);

15.because array names represent the address of the array, which is a constant and can’t be changed

16.reference; pointer

G

Q E UESTIONS ANSWERS XERCISES AND TO

Appendix G

950

17.a, d

18.void func(char*);

19.

for(int j=0; j<80; j++) *s2++ = *s1++;

20.b

21.char* revstr(char*);

22.char* numptrs[] = { “One”, “Two”, “Three” };

23.a, c

24.wasted

25.memory that is no longer needed

26.p->exclu();

27.objarr[7].exclu();

28.a, c

29.float* arr[8];

30.b

31.0..9 at one end; 3..* at the other

32.b

33.false

34.a

Solutions to Exercises

1.

//ex10_1.cpp

//finds average of numbers typed by user #include <iostream>

using namespace std;

int main()

 

{

 

float flarr[100];

//array for numbers

char ch;

//user decision

int num = 0;

//counts numbers input

do

 

{

 

 

Answers to Questions and Exercises

 

 

cout << “Enter number: “;

//get numbers from user

cin >> *(flarr+num++);

//until user answers ‘n’

cout << “ Enter another (y/n)?

“;

cin >> ch;

 

}

 

while(ch != ‘n’);

 

float total = 0.0;

//total starts at 0

for(int k=0; k<num; k++)

//add numbers to total

total += *(flarr+k);

 

float average = total / num;

//find and display average

cout << “Average is “ << average <<

endl;

return 0;

 

}

 

2.

//ex10_2.cpp

//member function converts String objects to upper case #include <iostream>

#include

<cstring>

//for

strcpy(),

etc

#include

<cctype>

//for

toupper()

 

using namespace std;

 

 

 

////////////////////////////////////////////////////////////////

class String

//user-defined string type

{

 

 

private:

 

 

char* str;

 

//pointer to string

public:

 

 

String(char* s)

 

//constructor, one arg

{

 

 

int length = strlen(s);

//length of string argument

str = new char[length+1];

//get memory

strcpy(str, s);

 

//copy argument to it

}

 

 

~String()

 

//destructor

{ delete str; }

 

 

void display()

 

//display the String

{ cout << str; }

 

 

void upit();

 

//uppercase the String

};

 

 

//--------------------------------------------------------------

 

 

void String::upit()

 

//uppercase each character

{

 

 

char* ptrch = str;

 

//pointer to this string

while( *ptrch )

 

//until null,

{

 

 

*ptrch = toupper(*ptrch);

//uppercase each character

951

G

Q E UESTIONS ANSWERS XERCISES AND TO

int main()
{
void bsort(char**, int);

Appendix G

952

ptrch++;

//move to next character

}

 

}

////////////////////////////////////////////////////////////////

int main()

{

String s1 = “He who laughs last laughs best.”;

cout << “\ns1=”;

//display string

s1.display();

 

s1.upit();

//uppercase string

cout << “\ns1=”;

//display string

s1.display();

 

cout << endl;

 

return 0;

 

}

 

3.

//ex10_3.cpp

//sort an array of pointers to strings #include <iostream>

#include <cstring>

//for strcmp(), etc.

using

namespace std;

 

const

int DAYS = 7;

//number of pointers in array

//prototype

//array of pointers to char char* arrptrs[DAYS] = { “Sunday”, “Monday”, “Tuesday”,

“Wednesday”, “Thursday”, “Friday”, “Saturday” };

cout <<

“\nUnsorted:\n”;

 

for(int

j=0; j<DAYS; j++)

//display unsorted strings

cout

<< *(arrptrs+j) << endl;

bsort(arrptrs, DAYS);

//sort the strings

cout <<

“\nSorted:\n”;

 

for(j=0; j<DAYS; j++)

//display sorted strings

cout

<< *(arrptrs+j) << endl;

return 0;

 

}

 

 

//--------------------------------------------------------------

 

 

void bsort(char** pp, int n)

//sort pointers to strings

{

 

 

Answers to Questions and Exercises

953

void order(char**,

char**);

//prototype

 

int j, k;

 

//indexes to

array

for(j=0; j<n-1; j++)

//outer loop

 

for(k=j+1; k<n;

k++)

//inner loop

starts at outer

order(pp+j, pp+k);

 

//order the pointer contents

}

 

 

 

//--------------------------------------------------------------

void order(char** pp1, char** pp2) //orders two pointers

{

//if string in 1st is

if( strcmp(*pp1, *pp2) > 0)

//larger than in 2nd,

{

 

char* tempptr = *pp1;

//swap the pointers

*pp1 = *pp2;

 

*pp2 = tempptr;

 

}

 

}

 

4.

//ex10_4.cpp

//linked list includes destructor #include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

struct link

//one element of list

{

 

int data;

//data item

link* next;

//pointer to next link

};

 

////////////////////////////////////////////////////////////////

class linklist

//a list of links

{

 

private:

 

link* first;

//pointer to first link

public:

 

linklist()

//no-argument constructor

{ first = NULL; }

//no first link

~linklist();

//destructor

void additem(int d);

//add data item (one link)

void display();

//display all links

};

 

//--------------------------------------------------------------

 

void linklist::additem(int d)

//add data item

{

 

link* newlink = new link;

//make a new link

newlink->data = d;

//give it data

G

Q E UESTIONS ANSWERS XERCISES AND TO

954

Appendix G

 

newlink->next = first;

//it points to next link

first = newlink;

//now first points to this

}

 

//--------------------------------------------------------------

 

void linklist::display()

//display all links

{

 

link* current = first;

//set ptr to first link

while( current != NULL )

//quit on last link

{

 

cout << endl << current->data;

//print data

current = current->next;

//move to next link

}

 

}

 

//--------------------------------------------------------------

 

linklist::~linklist()

//destructor

{

 

link* current = first;

//set ptr to first link

while( current != NULL )

//quit on last link

{

 

link* temp = current;

//save ptr to this link

current = current->next;

//get ptr to next link

delete temp;

//delete this link

}

 

}

 

////////////////////////////////////////////////////////////////

int main()

 

{

 

linklist li;

//make linked list

li.additem(25);

//add four items to list

li.additem(36);

 

li.additem(49);

 

li.additem(64);

 

li.display();

//display entire list

cout << endl;

 

return 0;

 

}

 

Chapter 11

Answers to Questions

1.d

2.true