C + + premier plus (Sixth Edition) Chapter 10 answers to object and class programming exercises

Posted by dannau on Sat, 25 Dec 2021 18:05:42 +0100

1. Provide method definitions for the classes described in review question 5, and write a small program to demonstrate all the features.
This question examines the declaration, definition and simple use of classes. It is not difficult. The sample code is as follows:
// account.h -- class defination for Account
#ifndef ACCOUNT_H_
#define ACCOUNT_H_

#include<string>

class BankAccount
{
    private:
        std::string name_;
        std::string acc_num_;
        double deposit_;
    public:
        BankAccount();
        BankAccount(const std::string & name, const std::string & acc_num, double cash);
        ~BankAccount();
        void show_account();
        void deposit_in(double cash);
        void deposit_out(double cash);
};

#endif
// account.cpp -- Account member function
#include <iostream>
#include "account.h"

BankAccount::BankAccount()
{
}

BankAccount::BankAccount(const std::string & name, const std::string & acc_num, double cash)
{
    name_ = name;
    acc_num_ = acc_num;
    deposit_ = cash;
}

BankAccount::~BankAccount()
{
}

void BankAccount::show_account()
{
    using std::cout;
    cout << "Name: " << name_ << ", account number: " 
         << acc_num_ << ", deposit: " << deposit_ << '\n';
}

void BankAccount::deposit_in(double cash)
{
    using std::cout;
    if(cash < 0)
    {
        cout << "The number of cash you deposit is negative; "
             << "transcation is aborted.\n";
    }
    else
        deposit_ += cash;
}

void BankAccount::deposit_out(double cash)
{
    using std::cout;
    if(cash < 0)
    {
        cout << "The number of cash you deposit is negative; "
             << "transcation is aborted.\n";
    }
    else if(cash > deposit_)
    {
        cout << "You can't take the cash morn than you have!"
             << "Transcation is aborted.\n";
    }
    else
        deposit_ -= cash;
}
// accounter.cpp -- test the class account
#include <iostream>
#include "account.h"


int main()
{
    using std::cout;
    using std::cin;
    BankAccount account;
    std::string name;
    std::string acc_num;
    double cash;
    cout << "Enter your name: ";
    getline(cin,name);
    cout << "Enter your account number: ";
    getline(cin,acc_num);
    cout << "Enter the cash: ";
    cin >> cash;
    account = BankAccount(name,acc_num,cash);
    account.show_account();
    cout << "Enter the cash you want to take in: ";
    cin >> cash;
    account.deposit_in(cash);
    account.show_account();
    cout << "Enter the cash you want to take out: ";
    cin >> cash;
    account.deposit_out(cash);
    account.show_account();
    return 0;
}

The operation results are as follows:

2. The following is a very simple class definition:

class Person
{
private:
    static const LIMIT = 25;
    std::string lname;
    char fname[LIMIT];
public:
    Person(){lname = "";fname[0] = '\0';};
    Person(const std::string & ln, const char * fn = "Heyyou");
// the following methods display lname and fname
    void Show()const;           // firstname lastname format
    void FormalShow() const;    // lastname, firstname format
};

It uses a string object and a character array to allow you to compare their usage. Please provide the code of the undefined method. The implementation of this class has been completed. Write another program using this class, which uses three possible constructor calls (no parameters, one parameter and two parameters) and two display methods. The following is an example of using these 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

This question mainly examines the implementation of class methods, and the function is also very simple. Compare string and char string arrays. When assigning values, one is assigned with = and the other is assigned with strcpy. The sample code is as follows:

// person.h -- protype class Person
#ifndef PERSON_H_
#define PRESON_H_

#include <string>

class Person
{
private:
    static const int LIMIT = 25;
    std::string lname;
    char fname[LIMIT];
public:
    Person(){lname = "";fname[0] = '\0';};                  // #1
    Person(const std::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
};
#endif
// person.cpp -- Person member function
#include <iostream>
#include <cstring>
#include "person.h"

Person::Person(const std::string & ln, const char * fn)
{
    lname = ln;
    strcpy(fname, fn);
}

void Person::Show() const
{
    using std::cout;
    cout << fname << " " << lname;
}

void Person::FormalShow() const
{
    std::cout << lname << ", " << fname << "\n";
}
// ex2_person.cpp -- test the class Person
#include <iostream>
#include "person.h"

int main()
{
    using std::cout;
    using std::endl;
    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
    two.Show();
    cout << endl;
    two.FormalShow();
    three.Show();
    cout << endl;
    three.FormalShow();
}

The operation results are as follows:

3. Complete programming exercise 1 in Chapter 9, but replace the code with the correct golf class declaration, and replace setgolf (Golf &, const char *, int) with a constructor with appropriate parameters to provide the initial value. Keep the interactive version of setgolf(), but use the constructor to implement it (for example, the code of setgolf() should get the data, pass the data to the constructor to create a temporary object and assign it to the calling object, * this).
The main content of this topic is the method of changing the structure into a class and the function of operating the structure into a class. Through modification, it is found that the parameter of the original function is the structure, which is changed into the object usage method. The sample code is as follows:

// golf.h -- definate Golf class

# ifndef GOLF_H_
# define GOLF_H_

class Golf
{
private:
    static const int Len = 40;
    char fullname[Len];
    int handicap;
public:
    Golf();
    Golf(const char * name, int hc);
    ~Golf();
    int setgolf();
    void set_handicap(int hc);
    void Show() const;
};
# endif
// golf.cpp -- member function of class Golf

#include <iostream>
#include <cstring>
#include "golf.h"

Golf::Golf()
{
}

Golf::Golf(const char * name, int hc)
{
    strcpy(fullname, name);
    handicap = hc;
}
Golf::~Golf()
{
}

int Golf::setgolf()
{
    using std::cout;
    using std::cin;
    using std::endl;
    Golf temp;
    cout << "Enter the users'name: ";
    cin.getline(temp.fullname, Len);
    if(!strcmp(temp.fullname,""))
        return 0;
    cout << "Enter the users'level: ";
    while(!(cin>>temp.handicap))
    {
        cin.clear();
        while(cin.get()!='\n')
            continue;
        cout << "Bad input, please enter a integer: ";
    }
    cin.get();
    *this = temp;
    return 1;
}

void Golf::set_handicap(int hc)
{
    handicap = hc;
}

void Golf::Show() const
{
     using std::cout;
    cout << "Name: " << fullname << ", level: " << handicap << "\n" ;
}
// ex3_usegolf.cpp -- test class Golf
// compile with golf.cpp
#include <iostream>
#include "golf.h"

const int Arsize = 5;
int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    int hd, number;
    int count = 0;
    Golf gar[Arsize];
    cout << "Enter the Users' name and level(enter empty string to name to quit):\n";
    for(int i = 0; i < Arsize; i++)
    {
        cout << "User #" << i + 1 << ":\n";
        int end_flag = gar[i].setgolf();
        if (end_flag == 0)
            break;
        count++;
    }
    for(int i = 0; i < count; i++)
    {
        cout << "User #" << i + 1 << ":\t";
        gar[i].Show();
    }
    // using handicap

    cout << "Enter the number of user you need to change level(q to quit): ";
    while(cin >> number)
    {
        cout << "The new Level: ";
        cin >> hd;
        gar[number - 1].set_handicap(hd);
        cout << "Enter next number(q to quit): "; 
    }
    cout << "The new golf users list:\n";
    for(int i = 0; i < count; i++)
    {
        cout << "User #" << i + 1 << ":\t";
        gar[i].Show();
    }
    cout << "Bye\n";
    return 0;
}

The operation results are as follows:

4. Complete the programming exercise 4 in Chapter 9, but convert the sales structure and related functions into a class and its methods. Replace the set (Sales &, double [], int) function with the constructor. Use the constructor to implement the interactive version of the setsales (Sales &) method. Keep the class in the namespace sales.
This question examines the definition of classes and class methods in the namespace, and there are not many codes to change. Note that class methods defined in the namespace also need to name the class and determine the scope. The sample code is as follows:

// sale.h store namespace for sale.cpp
// version class
namespace SALES
{
    const int QUARTERS = 4;
    class Sales
    {
    private:
        double sales[QUARTERS];
        double average;
        double max;
        double min;
    public:
        Sales();
        Sales(const double ar[], int n);
        void ShowSales() const;
    };
}
// sale.cpp -- membet function for Sales in namespace SALES
// compile with ex4_useSales.cpp
#include <iostream>
#include "sale.h"

static double find_min(const double ar[], int n);
static double find_max(const double ar[], int n);
static double getaverage(const double ar[], int n);
static double * find_4less(const double ar[], int n);

namespace SALES
{
    
    Sales::Sales()
    {
        using std::cout;
        using std::cin;
        cout << "Enter four sales:\n";
        for(int i = 0; i < 4; i++)
        {
            cout << "Sales #" << i + 1 << ": ";
            cin >> sales[i];
        }
        min = find_min(sales, 4);
        max = find_max(sales, 4);
        average = getaverage(sales, 4);
    }

    Sales::Sales(const double ar[], int n)
    {
        min = find_min(ar, n);
        max = find_max(ar, n);
        average = getaverage(ar,n);
        if(n <= 4)
        {
            int i;
            for(i = 0; i < n; i++)
                sales[i] = ar[i];
            for(;i < 4; i++)
                sales[i] = 0;
        }
        else
        {
            for(int i = 0; i < 4; i++)
                sales[i] = find_4less(ar, n)[i];
        }
    }

    void Sales::ShowSales() const
    {
        using std::cout;
        cout << "Sales list:\n";
        for(int i = 0; i < 4; i++)
        {
            cout << "Sales #" << i + 1 << ": ";
            cout << sales[i] << "\t";
        }
        cout << "\n";
        cout << "Average = " << average << ", max = " << max;
        cout << ", min = " << min << "\n";
    }
}

double find_min(const double ar[], int n)
{
    double min = ar[0];
    for(int i = 0; i < n; i++)
        min = min < ar[i] ? min : ar[i];
    return min;
}

double find_max(const double ar[], int n)
{
    double max = ar[0];
    for(int i = 0; i < n; i++)
        max = max < ar[i] ? ar[i] : max;
    return max;
}

double getaverage(const double ar[], int n)
{
    double sum = 0;
    for(int i = 0; i < n; i++)
        sum += ar[i];
    return sum / n;
}
static double * find_4less(const double ar[], int n)
{
    double * lesser4 = new double[4];
    double lesser;
    lesser4[0] = find_min(ar, n);
    for(int i = 1; i < 4; i++)
    {
        lesser = find_max(ar, n);
        for(int j = 0; j < n; j++)
        {
            if(ar[j] > lesser4[i-1])
                lesser = lesser < ar[j] ? lesser : ar[j]; 
        }
        lesser4[i] = lesser;
    }
    return lesser4;
}
// ex4_useSales.cpp -- using namespace and class
// compile with sale.cpp

#include <iostream>
#include "sale.h"

int main()
{
    using namespace SALES;
    using std::cout;
    Sales s1;
    double arr[6] = {1111.1, 666.6, 999.9, 333.3, 2222.2, 1234.5};
    Sales s2 = Sales(arr, 6);
    s1.ShowSales();
    s2.ShowSales();
    cout << "Bye\n";
    return 0;
}

The operation results are as follows:

5. Consider the following structural statement:

struct customer{
	char fullname[35];
	double payment;
}

Write a program that adds and removes the custom structure from the Stack (the Stack is represented by the Stack class declaration). Each time the customer structure is deleted, the value of its payment will be added to the total and the total will be reported. Note: you should be able to directly use the Stack class without modification; Just modify the typedef declaration so that the Item type is customer instead of unsigned long.

This problem encountered many problems in the process of writing. First, I don't understand the pop and push programs of stack. The top element of stack is empty. When pressing into the stack, I assign the element to the top element, and then the pointer Top + +. When popping up, first -- top, and then point top to the value of the element.
When using array implementation:
push stack[top++] = value; This program is equivalent to stack[top] = value;top++;
pop value = stack[--top]; The program is equivalent to -- top;value = stack[top];
The sample code is as follows:

// stack.h -- Class Stack protype and  member function protype
#ifndef STACK_H_
#define STACK_H_

const int NSIZE = 35;

struct customer
{
    char fullname[NSIZE];
    double payment;
};

typedef struct customer Item;

class Stack
{
private:
    static const int MAX = 10; // also enum{MAX = 10};
    Item items[MAX];
    int top;
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item & item);
    bool pop(Item & item);
};
#endif
// stack.cpp -- member function for stack class
// compile with ex4.cpp

#include <cstring>
#include "stack.h"

Stack::Stack()
{
    top = 0;
}

bool Stack::isempty() const
{
    return top == 0;
}

bool Stack::isfull() const
{
    return top == MAX;
}

bool Stack::push(const Item & item)
{
    if(isfull())
        return false;
    strcpy(items[top].fullname,item.fullname);
    items[top++].payment = item.payment;
    return true;
}

bool Stack::pop(Item & item)
{
    if(top > 0)
    {
        item = items[--top];
        return true;
    }
    else
        return false;
}
// ex4_usestack.cpp -- use stack class to store the custormer
// compile with stack.cpp
#include <iostream>
#include <cstring>
#include "stack.h"

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    Stack st;
    customer ct;
    double sum_pm = 0;
    int count = 0;
    cout << "Enter the customer name(enter empty string to quit): ";
    cin.getline(ct.fullname,NSIZE);
    while (strcmp(ct.fullname, ""))
    {
        cout << "Enter the payment: ";
        while(!(cin >> ct.payment))
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Bad input, please input a number: ";
        }
        cin.get();
        st.push(ct);
        if(st.isfull())
            break;
        cout << "Enter next customer name(enter empty string to quit): ";
        cin.getline(ct.fullname,NSIZE);
    }
    while(!st.isempty())
    {
        ++count;
        st.pop(ct);
        sum_pm += ct.payment;
        cout << count  << " customers' total payment is " << sum_pm << endl;
    }
    cout << "Bye\n";
    return 0;
}

The operation results are as follows:

6. The following is a class declaration:

class Move
{
private:
    double x;
    double y;
public:
    Move(double a = 0.0,double b = 0.0);    // sets x, y to a, b
    void 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 to y of invokeing object to get new y, create a new
// move object initialized to new x, y values and returns it
    void reset(double a = 0.0, double b = 0.0);  // resets x,t to a,b
};

Please provide the definition of member function and the program to test this class
This topic is relatively simple, that is, declaration class and test class. The sample code is as follows:

// move.h -- defination of Move class for move.cpp
// version

#ifndef MOVE_H_
#define MOVE_H_

class Move
{
private:
    double x;
    double y;
public:
    Move(double a = 0.0,double b = 0.0);    // sets x, y to a, b
    void 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 to y of invokeing object to get new y, create a new
// move object initialized to new x, y values and returns it
    void reset(double a = 0.0, double b = 0.0);  // resets x,t to a,b
};
#endif
// move.cpp -- member function of class Move
// compile with ex6_usemove.cpp

#include <iostream>
#include "move.h"

Move::Move(double a, double b)
{
    x = a;
    y = b;
}

void Move::showmove() const
{
    std::cout << "x = " << x << ", y = " << y << '\n';
}

Move Move::add(const Move & m) const
{
    Move temp;
    temp.x = x + m.x;
    temp.y = y + m.y;
    return temp;
}

void Move::reset(double a , double b)
{
    x = a;
    y = b;
}
// ex6_usemove.cpp -- test class Move
// compile with move.cpp

#include <iostream>
#include "move.h"

int main()
{
    using std::cin;
    using std::cout;
    Move point;
    double a, b;
    Move mv;
    Move result;
    cout << "Enter the point of x,y position: ";
    cin >> a >> b;
    point.reset(a,b);
    point.showmove();
    cout << "Enter the move x y: ";
    cin >> a >> b;
    mv.reset(a,b);
    result = point.add(mv);
    cout << "After move, the point of position is ";
    result.showmove();
    return 0;
}

The operation results are as follows:

7. Betelgeusean plorg has these characteristics.
Data:

  • The name of plorg shall not exceed 19 characters;
  • plorg has a satisfaction index (CI), which is an integer.

Operation:

  • The new plorg will have a name with a CI value of 50;
  • The CI of plorg can be modified;
  • plorg can report its name and CI;
  • The default name of plorg is "Plorga".

Please write a plorg class declaration (including member function and member function prototype) to represent plorg, and write the function definition of member function. Then write a small program to demonstrate all the features of plorg class.
This topic is relatively simple. First, convert the text in the topic into code. There are no problems. When writing the test main function, I encountered problems because of the priority ratio of CIN > > CI! Low, so there should be parentheses! (CIN > > CI), the sample code is as follows:

// plorg.h -- defination of class Plorg
// version 00

#ifndef PLORG_H_
#define PLORG_H_
const int NSIZE = 20;
class Plorg
{
private:
    char name_[NSIZE];
    int CI_;
public:
    Plorg();
    Plorg(const char * name, int CI = 50);
    void setCI(int CI);
    void ShowPlorg() const;
    void setname(const char * name = "Plorga");
};
#endif
// plorg.cpp -- member funciton of class Plorg
// compile with ex7_useplorg.cpp

#include <iostream>
#include <cstring>
#include "plorg.h"

Plorg::Plorg()
{
}

Plorg::Plorg(const char * name, int CI)
{
    strcpy(name_, name);
    CI_ = CI;
}

void Plorg::setCI(int CI)
{
    CI_ = CI;
}

void Plorg::ShowPlorg() const
{
    std::cout << "Plorg name: " << name_ << ", CI = " << CI_ << '\n';
}

void Plorg::setname(const char * name)
{
    strcpy(name_,name);
}
// ex7_useplorg.cpp -- test class Plorg
// compile with plorg.cpp

#include <iostream>
#include <cstring>
#include "plorg.h"

const int PSize = 10;
int main()
{
    using std::cout;
    using std::cin;
    Plorg plorg[PSize];
    Plorg pl = Plorg("Jobs Sam",60);
    pl.ShowPlorg();
    char name[NSIZE];
    int CI;
    int count = 0;
    for(int i = 0; i < PSize; i++)
    {
        cout << "The plorg #" << i + 1 << ":\n";
        cout << "Enter the name(enter empty string to quit): ";
        cin.getline(name, NSIZE);
        if(!strcmp(name,""))
            break;
        count++;
        cout << "Enter the CI: ";
        while(!(cin >> CI)) // () is must
        {
            cin.clear();
            while(cin.get() != '\n')
                continue;
            cout << "Bad input, please input a integer: ";
        }
        cin.get();
        plorg[i].setname(name);
        plorg[i].setCI(CI);
    }
    cout << "Plorg List:\n" ;
    for(int i = 0; i < count; i++)
        plorg[i].ShowPlorg();

    cout << "Bye\n";

}

The operation results are as follows:

8. A simple list can be described as follows:

  • It can store 0 or more lists of some type;
  • You can create an empty list;
  • Data items can be added to the list;
  • You can determine whether the list is empty;
  • You can determine whether the list is full;
  • You can access each data item in the list and perform some operation on it.

As you can see, this list is really simple. For example, it does not allow inserting or deleting data items. You should provide the header file list H and implementation file list CPP, the former contains class definitions and the latter contains the implementation of class methods. You should also create a simple program to use this class.
The specification of the list is simple, which is mainly intended to simplify this programming exercise. You can choose to use array or linked list to implement the list, but the public interface should not depend on the selection, that is, the public interface should not have array index, node pointer, etc. Common concepts should be used to express operations such as creating lists, adding data items to lists, and so on. For accessing data items and performing operations, you should usually use functions with function pointers as parameters:
void visit(void (*pf) (Item &))
Where pf points to a function (not a member function) that takes an item reference as a parameter. Item is the type of data item in the list. The visit() function uses this function for each data item in the list.
Because the author has not learned the linked list at present, he does not use the linked list and uses the array to store it. There are problems when writing the program. There are problems with the visit function. After understanding the function as a parameter, he writes the program. The test program is relatively simple. After learning the linked list, he will improve the program and realize the benefits of object-oriented programming. The code is as follows:

// list.h -- protype class list
// version 00

#ifndef LIST_H_
#define LIST_H_
typedef double Item;
class List
{
private:
    enum{MAX = 10};
    Item items[MAX];
    int header;
public:
    List();
    List(const Item * aritem, int n);
    bool add_data(const Item & item);
    bool isempty() const;
    bool isfull() const;
    void visit(void (*pf) (Item & item));
};
#endif
// list.cpp -- member function of class List
// compile with ex8_uselist.cpp

#include <iostream>
#include "list.h"

List::List()
{
    header = 0;
}

List::List(const Item * aritem, int n)
{
    for(header = 0; header < n; header++)
    {
        items[header] = aritem[header]; 
    }
}

bool List::add_data(const Item & item)
{
    if(header < MAX)
    {
        items[header++] = item;
        return true;
    }
    else
        return false;
}

bool List::isempty() const
{
    return header == 0;
}

bool List::isfull() const
{
    return header == MAX;
}

void List::visit(void (*pf) (Item & item))
{
    for(int i = 0; i < header; i++)
        (*pf)(items[i]);
}
// ex8_uselist.cpp -- test class List
// compile with list.cpp

#include <iostream>
#include "list.h"
void Show(Item & item);
int main()
{
    using std::cout;
    Item num;
    List ld1;
    double arr[10] = {1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0};
    if(ld1.isempty())
        cout << "List of double is empty\n";
    List ld2 = List(arr,10);
    if(ld2.isfull())
        cout << "List of double is full\n";
    ld2.visit(Show);
    cout << '\n';
    cout << "Before add data:\n";
    ld1.visit(Show);
    cout << '\n';
    cout << "Enter the number you want to add: ";
    std::cin >> num;
    ld1.add_data(num);
    cout << "After add data:\n";
    ld1.visit(Show);
    cout << '\n';
    cout << "Bye\n";
    return 0;
}
void Show(Item & item)
{
    std::cout << item << " "; 
}

The operation results are as follows:

Topics: C++