Sunteți pe pagina 1din 29

1.

Provide method definitions for the class described in Review Question 5 and write a
short program that illustrates all the features.
My answer:
bankaccount.h
1 #ifndef BANKACCOUNT_H_
2 #define BANKACCOUNT_H_
3
4 #include <iostream>
5 #include <string>
6
7 class BankAccount
8 {
9 private:
10 std::string DepositorName;
11 std::string AccountNumber;
12 double Balance;
13public:
14 BankAccount();
15 BankAccount(std::string depname, std::string acnum, double bal);
16 ~BankAccount();
17 void ShowInfo() const;
18 void Withdraw(double amount);
19 void Deposit(double depamount);
20};
21
22#endif
bankaccount.cpp
1 #include "bankaccount.h";
2
3 BankAccount::BankAccount()
4 {

DepositorName = "No Name";

AccountNumber = "00000000";

Balance = 0;

8 }
9
10BankAccount::BankAccount(std::string depname, std::string acnum, double bal)
11{
12 DepositorName = depname;
13 AccountNumber = acnum;
14 Balance = bal;
15}
16
17BankAccount::~BankAccount()
18{
19}
20
21void BankAccount::ShowInfo() const
22{
23 using namespace std;
24 cout.precision(2);
25 cout.setf(ios_base::fixed, ios_base::floatfield);
26 cout.setf(ios_base::showpoint);
27 cout << "\nDepositor's name: " << DepositorName;
28 cout << "\nAccount number: " << AccountNumber;
29 cout << "\nBalance: $" << Balance;
30}
31
32void BankAccount::Withdraw(double amount)
33{
34 if (amount < 0)
35

std::cout << "\nPlease enter positive number for the amount to withdraw.";

36 else
37

Balance -= amount;

38}
39
40void BankAccount::Deposit(double depamount)
41{
42 if (depamount < 0)
43

std::cout << "\nPlease enter positive number for the amount to diposit.";

44 else
45

Balance += depamount;

46}
cp10ex1.cpp
1 #include <iostream>
2 #include "bankaccount.h"
3
4 int main()
5 {
6

using namespace std;

7
8

BankAccount Alex("Alex Ignatkov","04852214896",20000);

Alex.ShowInfo();

10
11 BankAccount Empty;
12 Empty.ShowInfo();
13
14 Alex.Withdraw(15000.13);
15 Alex.ShowInfo();
16 Alex.Deposit(7500.25);
17 Alex.ShowInfo();
18
19 Empty.Deposit(5000.45);

20 Empty.ShowInfo();
21
22 cin.get();
23 cin.get();
24 return 0;
25}

2. Here is a rather simple class definition:


class Person {
private:
static const LIMIT = 25;
string lname; // Persons last name
char fname*LIMIT+; // Persons first name
public:
496 C++ PRIMER PLUS, FIFTH EDITION
Person() ,lname = ; fname*0+ = \0; - // #1
Person(const string & ln, const char * fn = Heyyou); // #2
// the following methods display lname and fname
void Show() const; // firstname lastname format
void FormalShow() const; // lastname, firstname format
};
Write a program that completes the implementation by providing code for the undefined
methods. The program in which you use the class should also use the three possible
constructor calls (no arguments, one argument, and two arguments) and the two display
methods. Heres an example that uses the constructors and methods:
Person one; // use default constructor
Person two(Smythecraft); // use #2 with one default argument
Person three(Dimwiddy, Sam); // use #2, no defaults
one.Show();
cout << endl;
one.FormalShow();
// etc. for two and three
My answer:
person.h
1 #ifndef PERSON_H_
2 #define PERSON_H_
3
4 #include <string>

5 #include <iostream>
6
7 class Person {
8

private:

static const int LIMIT = 25;

10

std::string lname; // Persons last name

11

char fname*LIMIT+; // Persons first name

12 public:
13

Person() ,lname = ""; fname*0+ = \0; - // #1

14

Person(const std::string & ln, const char * fn = "Heyyou"); // #2

15

~Person();

16

// the following methods display lname and fname

17

void Show() const; // firstname lastname format

18

void FormalShow() const; // lastname, firstname format

19};
20
21#endif
person.cpp
1 #include "person.h"
2
3 Person::Person(const std::string & ln, const char * fn)
4 {
5

lname = ln;

strcpy(fname,fn);

7 }
8
9 Person::~Person()
10{
11}
12
13void Person::Show() const

14{
15 std::cout << "\n" << fname << " " << lname;
16}
17
18void Person::FormalShow() const
19{
20 std::cout << "\n" << lname << ", " << fname;
21}
cp10ex2.cpp
1 #include "person.h"
2 int main()
3 {
4

using namespace std;

5
6

Person one; // use default constructor

Person two("Smythecraft"); // use #2 with one default argument

Person three("Dimwiddy", "Sam"); // use #2, no defaults

one.Show();

10 cout << endl;


11 one.FormalShow();
12 two.FormalShow();
13 two.Show();
14 three.FormalShow();
15 three.Show();
16
17 cin.get();
18 cin.get();
19 return 0;
20}

One Response to C++ Primer Plus Chapter 10 Exercise 2 Answer

1.

Daniel says:
April 2, 2013 at 6:49 am
Why it generated the error LNK2019?

3. Do Programming Exercise 1 from Chapter 9, but replace the code shown there with an
appropriate golf class declaration. Replace setgolf(golf &, const char *, int)
with a constructor with the appropriate argument for providing initial values. Retain the
interactive version of setgolf(), but implement it by using the constructor. (For example,
for the code for setgolf(), obtain the data, pass the data to the constructor to create
a temporary object, and assign the temporary object to the invoking object, which is
*this.)
My answer:
golf.h
1 #ifndef GOLF_H_
2 #define GOLF_H_
3
4 #include <iostream>
5
6 class Golf
7 {
8 private:
9

const static int Len = 40;

10 char fullname[Len];
11 int handicap;
12 int setgolf(Golf & g);
13public:
14 // non-interactive version:
15 // function sets golf structure to provided name, handicap
16 // using values passed as arguments to the function
17 Golf(const char * name, int hc);
18 // interactive version:

19 // function solicits name and handicap from user


20 // and sets the members of g to the values entered
21 // returns 1 if name is entered, 0 if name is empty string
22 Golf ();
23 // function resets handicap to new value
24 void Resethandicap(int hc);
25 // function displays contents of golf structure
26 void Showgolf() const;
27};
28
29#endif
golf.cpp
1 #include "golf.h"
2
3 // non-interactive version:
4 // function sets golf structure to provided name, handicap
5 // using values passed as arguments to the function
6 Golf::Golf(const char * name, int hc)
7 {
8

strcpy(fullname,name);

handicap = hc;

10}
11// interactive version:
12// function solicits name and handicap from user
13// and sets the members of g to the values entered
14// returns 1 if name is entered, 0 if name is empty string
15Golf::Golf()
16{
17 setgolf(*this);
18}
19

20// function resets handicap to new value


21void Golf::Resethandicap(int hc)
22{
23 handicap = hc;
24}
25// function displays contents of golf structure
26void Golf::Showgolf() const
27{
28 using namespace std;
29 cout << "\n\nDisplaying Golf structure:";
30 cout << "\nGolfer's name is " << fullname;
31 cout << "\nGolfer's handicap # is " << handicap;
32}
33
34int Golf::setgolf(Golf & g)
35{
36 using namespace std;
37 cout << "\nEnter golfer's name: ";
38 cin.getline(g.fullname,Len);
39 if (g.fullname[0] =='\0')
40

return 0;

41
42 cout << "\nEnter handicap number: ";
43 cin >> g.handicap;
44 return 1;
45}
cp10ex3.cpp
1 #include <iostream>
2 #include "golf.h"
3
4 int main()

5 {
6
7

using namespace std;

8
9

Golf ann;

10 ann.Showgolf();
11 ann.Resethandicap(50);
12 ann.Showgolf();
13
14 Golf alex("Alex Ignatkov",23);
15 alex.Showgolf();
16 alex.Resethandicap(17);
17 alex.Showgolf();
18
19 cin.get();
20 cin.get();
21 return 0;
22}

4. Do Programming Exercise 4 from Chapter 9, but convert the Sales structure and its
associated functions to a class and its methods. Replace the setSales(Sales &, double
[], int) function with a constructor. Implement the interactive setSales(Sales &)
method by using the constructor. Keep the class within the namespace SALES.
My answer:
sales.h
1 #ifndef SALES_H_
2 #define SALES_H_
3
4 namespace SALES
5 {
6

class Sales

private:

const static int QUARTERS = 4;

10

double sales[QUARTERS];

11

double average;

12

double max;

13

double min;

14 public:
15

// copies the lesser of 4 or n items from the array ar

16

// to the sales member of s and computes and stores the

17

// average, maximum, and minimum values of the entered items;

18

// remaining elements of sales, if any, set to 0

19

Sales(const double ar[], int n);

20

// gathers sales for 4 quarters interactively, stores them

21

// in the sales member of s and computes and stores the

22

// average, maximum, and minumum values

23

Sales();

24

~Sales();

25

// display all information in structure s

26

void showSales() const;

27 };
28}
29
30#endif
sales.cpp
1 #include <iostream>
2 #include "sales.h"
3
4 namespace SALES
5 {
6

using std::cout;

using std::cin;

using std::endl;

9 // copies the lesser of 4 or n items from the array ar


10// to the sales member of s and computes and stores the
11// average, maximum, and minimum values of the entered items;
12// remaining elements of sales, if any, set to 0
13 Sales::Sales(const double ar[], int n)
14 {
15

int numsales = n < QUARTERS ? n : QUARTERS;

16

double total = 0;

17
18

min = max = ar[0];

19

for (int i = 0; i < numsales; i++)

20

21

sales[i] = ar[i];

22

if (min > ar[i])

23

min = ar[i];

24

else if (max < ar[i])

25

max = ar[i];

26

total += ar[i];

27

28

average = total / numsales;

29
30
31

for (int i = numsales; i < QUARTERS; i++)


sales[i] = 0;

32 }
33// gathers sales for 4 quarters interactively, stores them
34// in the sales member of s and computes and stores the
35// average, maximum, and minumum values
36 Sales::Sales()
37 {
38

double qt,total = 0;

39
40

cout << endl;

41

for (int i = 0; i < QUARTERS; i++)

42

43

cout << "Enter sales for quarter #" << i+1 << ": ";

44

cin >> qt;

45

sales[i] = qt;

46

total += qt;

47

48
49

min = max = sales[0];

50

for (int i = 0; i < QUARTERS; i++)

51

52

if (min > sales[i])

53

min = sales[i];

54

else if (max < sales[i])

55
56

max = sales[i];
}

57
58

average = total / QUARTERS;

59
60 }
61
62// display all information in structure s
63 void Sales::showSales() const
64 {
65

cout << "\nDisplaying Sales structure.";

66

for (int i = 0; i < QUARTERS; i++)

67

cout << "\nSales Quarter #" << i+1 << ": " << sales[i];

68

cout << "\nMin = " << min;

69

cout << "\nMax = " << max;

70

cout << "\nAverage = " << average;

71 }
72
73 Sales::~Sales()
74 {
75 }
76
77}
cp10ex4.cpp
1 #include <iostream>
2 #include "sales.h"
3
4 int main()
5 {
6

double ar[3] = {100,200,300};

SALES::Sales s1;

SALES::Sales s2(ar,3);

9
10 s1.showSales();
11 s2.showSales();
12
13 std::cin.get();
14 std::cin.get();
15 return 0;
16}

5. Consider the following structure declaration:


struct customer {
char fullname[35];
double payment;
};
Write a program that adds and removes customer structures from a stack, represented by
a Stack class declaration. Each time a customer is removed, his or her payment should

be added to a running total, and the running total should be reported. Note: You should
be able to use the Stack class unaltered; just change the typedef declaration so that
Item is type customer instead of unsigned long.
My answer:
stack.h
1 // stack.h -- class definition for the stack ADT
2 #ifndef STACK_H_
3 #define STACK_H_
4
5 struct customer {
6 char fullname[35];
7 double payment;
8 };
9
10typedef customer Item;
11
12class Stack
13{
14 private:
15

enum {MAX = 10}; // constant specific to class

16

Item items[MAX]; // holds stack items

17

int top; // index for top stack item

18 public:
19

Stack();

20

bool isempty() const;

21

bool isfull() const;

22

// push() returns false if stack already is full, true otherwise

23

bool push(const Item & item); // add item to stack

24

// pop() returns false if stack already is empty, true otherwise

25

bool pop(Item & item); // pop top into item

26};

27#endif
stack.cpp
1 // stack.cpp -- Stack member functions
2 #include "stack.h"
3
4 Stack::Stack() // create an empty stack
5 {
6

top = 0;

7 }
8 bool Stack::isempty() const
9 {
10 return top == 0;
11}
12bool Stack::isfull() const
13{
14 return top == MAX;
15}
16bool Stack::push(const Item & item)
17{
18 if (top < MAX)
19 {
20

items[top++] = item;

21

return true;

22 }
23 else
24

return false;

25}
26bool Stack::pop(Item & item)
27{
28 if (top > 0)
29 {

30

item = items[--top];

31

return true;

32 }
33 else
34

return false;

35}
cp10ex5.cpp
1 #include <iostream>
2 #include <cctype> // or ctype.h
3 #include "stack.h"
4
5 int main()
6 {
7

using namespace std;

8
9

Stack st; // create an empty stack

10 char ch;
11 customer po;
12 double runtotal = 0;
13
14 cout << "Please enter A to add a customer,\n"
15

<< "R to remove a customer from stack, or Q to quit.\n";

16 while (cin >> ch && toupper(ch) != 'Q')


17 {
18

while (cin.get() != '\n')

19

continue;

20

if (!isalpha(ch))

21

22

cout << '\a';

23

continue;

24

25

switch(ch)

26

27

case 'A':

28

case 'a': cout << "Enter a customer's FULL NAME: ";

29

cin.getline(po.fullname,35);

30

cout << "Enter a payment for " << po.fullname << " : ";

31

cin >> po.payment;

32

if (st.isfull())

33

cout << "stack already full\n";

34

else

35

st.push(po);

36

break;

37

case 'R':

38

case 'r': if (st.isempty())

39

cout << "stack already empty\n";

40

else

41

42

st.pop(po);

43

runtotal += po.payment;

44
removed\n";
45

cout << "Customer " << po.fullname << " with payment of " << po.payment << " is
}

46

break;

47
}

48
49

cout << "Please enter A to add a customer,\n"

50

<< "R to remove a customer from stack, or Q to quit.\n";

51
52

53
54
55

cout << "\nRunning Total = " << runtotal;


cout << "\nBye";

56 cin.get();
57 cin.get();
58 return 0;
}

6. Heres a class declaration:


class Move
{
private:
double x;
double y;
public:
Move(double a = 0, double b = 0); // sets x, y to a, b
showmove() const; // shows current x, y values
Move add(const Move & m) const;
// this function adds x of m to x of invoking object to get new x,
// adds y of m to y of invoking object to get new y, creates a new
// move object initialized to new x, y values and returns it
reset(double a = 0, double b = 0); // resets x,y to a, b
};
Create member function definitions and a program that exercises the class.
My answer:
move.h
1 #ifndef MOVE_H_
2 #define MOVE_H_
3
4 class Move
5 {
6

private:

double x;

double y;

public:

10

Move(double a = 0, double b = 0); // sets x, y to a, b

11

void showmove() const; // shows current x, y values

12

Move add(const Move & m) const;

13

// this function adds x of m to x of invoking object to get new x,

14

// adds y of m to y of invoking object to get new y, creates a new

15

// move object initialized to new x, y values and returns it

16

void reset(double a = 0, double b = 0); // resets x,y to a, b

17};
18
19#endif
move.cpp
1 #include "move.h"
2 #include <iostream>
3
4 Move::Move(double a, double b)
5 {
6

x = a;

y = b;

8 }
9
10void Move::showmove() const
11{
12 std::cout << "x = " << x << ", y = " << y;
13}
14
15Move Move::add(const Move &m) const
16{
17 Move temp;
18 temp.x = x + m.x;
19 temp.y = y + m.y;
20
21 return temp;
22}

23
24void Move::reset(double a, double b)
25{
26 x = a;
27 y = b;
28}
cp10ex6.cpp
1 #include <iostream>
2 #include "move.h"
3
4 int main()
5 {
6
7

Move obj1(5,6);

Move obj2(10,11);

Move obj3;

10
11 obj1 = obj1.add(obj2);
12 std::cout << "obj1: ";
13 obj1.showmove();
14
15 obj2 = obj2.add(obj1);
16 std::cout << "\nobj2: ";
17 obj2.showmove();
18
19 obj3 = obj1.add(obj2);
20 std::cout << "\nobj3: ";
21 obj3.showmove();
22
23 std::cin.get();
24 std::cin.get();

25 return 0;
26}

7. A Betelgeusean plorg has these properties:


Data
A plorg has a name with no more than 19 letters.
A plorg has a contentment index (CI), which is an integer.
Operations
A new plorg starts out with a name and a CI of 50.
A plorgs CI can change.
A plorg can report its name and CI.
The default plorg has the name Plorga.
Write a Plorg class declaration (including data members and member function prototypes)
that represents a plorg. Write the function definitions for the member functions.
Write a short program that demonstrates all the features of the Plorg class.
My answer:
plorg.h
1 #ifndef PLORG_H_
2 #define PLORG_H_
3
4 class Plorg
5 {
6 private:
7

enum {MAX = 19};

char fullname[MAX];

int CI;

10public:
11 Plorg();
12 Plorg(const char * fn, int CIvalue);
13 void Show() const;
14 void ChangeCI(int newCI) { CI = newCI;}
15};
16

17#endif
plorg.cpp
1 #include <iostream>
2 #include "plorg.h"
3
4 Plorg::Plorg()
5 {
6

CI = 50;

strcpy(fullname,"Plorga");

8 }
9
10Plorg::Plorg(const char *fn, int CIvalue)
11{
12 strcpy(fullname,fn);
13 CI = CIvalue;
14}
15
16void Plorg::Show() const
17{
18 std::cout << "\nName is " << fullname;
19 std::cout << "\nCI is " << CI;
20}
cp10ex7.cpp
1 #include <iostream>
2 #include "plorg.h"
3
4 int main()
5 {
6

Plorg Sample;

Sample.Show();

Plorg Sample2("Sample2",20);

10 Sample2.Show();
11
12 Sample.ChangeCI(30);
13 Sample.Show();
14
15 Sample2.ChangeCI(100);
16 Sample2.Show();
17
18 std::cin.get();
19 std::cin.get();
20 return 0;
21}

8. You can describe a simple list as follows:


The simple list can hold zero or more items of some particular type.
You can create an empty list.
You can add items to the list.
You can determine whether the list is empty.
You can determine whether the list is full.
You can visit each item in the list and perform some action on it.
As you can see, this list really is simple; it doesnt allow insertion or deletion, for
example.
Design a List class to represent this abstract type. You should provide a list.h header
file with the class declaration and a list.cpp file with the class method implementations.
You should also create a short program that utilizes your design.
The main reason for keeping the list specification simple is to simplify this programming
exercise. You can implement the list as an array or, if youre familiar with the data type,
as a linked list. But the public interface should not depend on your choice. That is, the
public interface should not have array indices, pointers to nodes, and so on. It should be
expressed in the general concepts of creating a list, adding an item to the list, and so on.
The usual way to handle visiting each item and performing an action is to use a function
that takes a function pointer as an argument:
void visit(void (*pf)(Item &));
Here pf points to a function (not a member function) that takes a reference to Item
argument, where Item is the type for items in the list. The visit() function applies this
function to each item in the list. You can use the Stack class as a general guide.
My answer:
list.h

1 #ifndef LIST_H_
2 #define LIST_H_
3
4 #include <iostream>
5 #include <string>
6
7 struct computergame
8 {
9

std::string gamename;

10 double price;
11};
12
13typedef computergame Item;
14
15class List
16{
17private:
18 enum {MAX = 10};
19 Item list[MAX];
20 int itemcount;
21public:
22 List();
23 bool isempty() const;
24 bool isfull() const;
25 int count() const;
26 bool add(const Item & item);
27 void priceadjust(void (*pf)(Item &));
28 void showlist();
29};
30
31#endif

list.cpp
1 #include "list.h"
2
3 List::List() // create an empty stack
4 {
5

itemcount = 0;

6 }
7 bool List::isempty() const
8 {
9

return itemcount == 0;

10}
11bool List::isfull() const
12{
13 return itemcount == MAX;
14}
15bool List::add(const Item & item)
16{
17 if (itemcount < MAX)
18 {
19

list[itemcount++] = item;

20

return true;

21 }
22 else
23

return false;

24}
25int List::count() const
26{
27 return itemcount;
28}
29
30void List::priceadjust(void (*pf)(Item &))

31{
32 for (int i = 0; i < itemcount; i++)
33

pf(list[i]);

34}
35
36void List::showlist()
37{
38 using namespace std;
39 cout.precision(2);
40 cout.setf(ios_base::fixed, ios_base::floatfield);
41 cout.setf(ios_base::showpoint);
42
43 for (int i = 0; i < itemcount; i++)
44

std::cout << "\nGame #" << i+1 << ": " << list[i].gamename << ", price - $" << list[i].price << ".";

45}
cp10ex8.cpp
1 #include "list.h"
2
3 inline void inflatrate(Item & gm) { gm.price *= 1.15;}
4
5 int main()
6 {
7
8

using namespace std;

9
10 List l1;
11 Item mygame;
12
13 cout << "Please enter computer games you own with price (Q to quit) :\n";
14 cout << "Name of game: ";
15 while(!l1.isfull() && getline(cin,mygame.gamename) && mygame.gamename[0] != '\0')

16 {
17

if (mygame.gamename == "Q" || mygame.gamename == "q")

18

break;

19
20

cout << "Price of game: ";

21

(cin >> mygame.price).get();

22
23

l1.add(mygame);

24

cout << "\nNext...\n";

25

cout << "Name of game: ";

26 }
27
28 cout << "\nItems entered: " << l1.count();
29
30 if (l1.isempty())
31

cout << "\nList is empty.";

32 else
33 {
34

l1.showlist();

35

cout << "\n\nPrice after inflation rate adjustment: \n";

36

l1.priceadjust(inflatrate);

37

l1.showlist();

38 }
39
40 std::cin.get();
41 std::cin.get();
42 return 0;
43}

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