C++ Primer Plus 第六版(中文版)第十章(完美修订版)编程练习答案(开始使用类和对象)

//本章程序需分多文件运行,请读者注意;

//本博主所写的代码仅为阅读者提供参考;

//若有不足之处请提出,博主会尽所能修改;

//附上课后编程练习题目;

//若是对您有用的话请点赞或分享提供给它人;

//--------------------------------------------------------------------
//10.10 - 1(main).cpp

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

int main()
{
    
    
    using std::cout;
    using std::endl;

    BankAccount temp("Clover", "1002", 666);

    cout << "Information of depositors:" << endl;
    temp.show();
    cout << "\nDeposit -1 dollar:" << endl;
    temp.deposit(-1);
    cout << "\nDeposit 100 dollars:" << endl;
    temp.deposit(100);
    cout << "\nWithdraw 6666 dollars:" << endl;
    temp.withdraw(6666);
    cout << "\nWithdraw 99 dollars:" << endl;
    temp.withdraw(99);
    cout << "\nNow information of depositors:" << endl;
    temp.show();
    cout << "Bye." << endl;

    return 0;
}

//10.10 - 1(bankaccount).h

#ifndef BANKACCOUNT_H_
#define BANKACCOUNT_H_
#include <string>

class BankAccount
{
    
    
private:
    std::string name;
    std::string acctnum;
    double balance;

public:
    BankAccount();
    BankAccount(const std::string &client, const std::string &num, double bal = 0.0); //默认参数函数,用户构造函数;
    void show() const;
    void deposit(double cash);
    void withdraw(double cash);
};

#endif

//10.10 - 1(bankaccount).cpp

#include <iostream>
#include <string>
#include "bankaccount.h"

BankAccount::BankAccount() //默认构造函数;
{
    
    
    name = "no name";
    acctnum = "no acctnum";
    balance = 0.0;
}

BankAccount::BankAccount(const std::string &client, const std::string &num, double bal) //用户构造函数;
{
    
    
    name = client;
    acctnum = num;
    balance = bal;
}

void BankAccount::show() const
{
    
    
    using std::cout;
    using std::endl;

    cout << "Name: " << name << endl;
    cout << "Acctnum: " << acctnum << endl;
    cout << "Balance: " << balance << endl;
    return;
}

void BankAccount::deposit(double cash)
{
    
    
    using std::cout;
    using std::endl;

    if (cash <= 0) //存款数额不能小于0;
    {
    
    
        cout << "Your deposit amount can't be less than 0!" << endl;
        return;
    }
    balance += cash;
    cout << "You deposit $" << cash << " successfully." << endl;
    return;
}

void BankAccount::withdraw(double cash)
{
    
    
    using std::cout;
    using std::endl;

    if (balance < cash) //取款数大于当前账户金额时的情况;
    {
    
    
        cout << "You can't withdraw more than your deposit!" << endl;
        return;
    }
    else if (cash <= 0) //取款数小于等于0时的情况;
    {
    
    
        cout << "Your withdrawal amount can't be less than 0!" << endl;
        return;
    }
    balance -= cash;
    cout << "You withdraw $" << cash << " successfully." << endl;
    return;
}

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

//--------------------------------------------------------------------
//10.10 - 2(main).cpp

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

int main()
{
    
    
    using std::cout;
    using std::endl;

    Person one;
    Person two("Smythecraft");
    Person three("Dimwiddy", "Sam");
    one.Show();
    one.FormalShow();
    cout << endl;
    two.Show();
    two.FormalShow();
    cout << endl;
    three.Show();
    three.FormalShow();
    cout << endl;

    return 0;
}

//10.10 - 2(person).h

#ifndef PERSON_H_
#define PERSON_H_
#include <string>
using namespace std;

class Person
{
    
    
private:
    static const int LIMIT = 25;
    string lname;
    char fname[LIMIT];

public:
    Person() //默认构造函数声明和定义;
    {
    
    
        lname = "";
        fname[0] = '\0';
    }
    Person(const string &ln, const char *fn = "Heyyou"); //用户构造函数;
    void Show() const;
    void FormalShow() const;
};

#endif

//10.10 - 2(person).cpp

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

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

void Person::Show() const
{
    
    
    std::cout << "The name format is:" << endl;
    std::cout << fname << "(firstname), ";
    std::cout << lname << "(lastname)." << endl;
    return;
}

void Person::FormalShow() const
{
    
    
    std::cout << "The name format is:" << endl;
    std::cout << lname << "(lastname), ";
    std::cout << fname << "(firstname)." << endl;
    return;
}

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

//--------------------------------------------------------------------
//10.10 - 3(main).cpp

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

int main()
{
    
    
    using std::cout;
    using std::endl;

    Golf temp1;
    Golf temp2("Cloverx", 666);

    cout << "The starting information1:" << endl;
    temp1.showgolf();
    temp1.set_handicap(998);
    cout << "After changing the handicap1:" << endl;
    temp1.showgolf();
    cout << "The starting information2:" << endl;
    temp2.showgolf();
    temp2.set_handicap(888);
    cout << "After changing the handicap2:" << endl;
    temp2.showgolf();

    return 0;
}

//10.10 - 3(golf).h

#ifndef GOLF_H_
#define GOLF_H_

class Golf
{
    
    
private:
    static const int Len = 40;
    char fullname[Len];
    int handicap;

public:
    Golf(const char *name, int hc); //默认构造函数;
    Golf();                         //用户定义构造函数;
    void set_handicap(int hc);
    void showgolf() const;
};

#endif

//10.10 - 3(golf).cpp

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

Golf::Golf(const char *name, int hc)
{
    
    
    strncpy(this->fullname, name, 40);
    this->fullname[39] = '\0';
    this->handicap = hc;
}

Golf::Golf()
{
    
    
    using std::cin;
    using std::cout;
    char tempname[40];
    int temphandicap;

    cout << "Please enter the fullname(enter to quit): ";
    cin.getline(tempname, Len);
    cout << "Please enter the handicap: ";
    while (!(cin >> temphandicap))
    {
    
    
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "Please enter an number: ";
    }
    cin.get();
    *this = Golf(tempname, temphandicap); //调用默认构造函数创建一个临时对象赋值给调用对象;
}

void Golf::set_handicap(int hc)
{
    
    
    this->handicap = hc;
    return;
}

void Golf::showgolf() const
{
    
    
    using namespace std;
    cout << "Name: " << this->fullname << endl;
    cout << "Handicap: " << this->handicap << endl;
    return;
}

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

//--------------------------------------------------------------------
//10.10 - 4(main).cpp

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

int main()
{
    
    
    using namespace SALES;
    double temp[4] = {
    
    1.0, 2.0, 3.0, 4.0};
    Sales objects[2] = {
    
    Sales(temp, 4), Sales()}; //首元素默认初始化,次元素用户初始化;

    std::cout << "The first object information:" << std::endl;
    objects[0].show_sales();
    std::cout << "The second object information:" << std::endl;
    objects[1].show_sales();
    std::cout << "Bye." << std::endl;

    return 0;
}

//10.10 - 4(sales).h

#ifndef SALES_H_
#define SALES_H_

namespace SALES
{
    
    
    class Sales
    {
    
    
    private:
        static const int QUARTERS = 4;
        double sales[QUARTERS];
        double average;
        double max;
        double min;

    public:
        Sales(double ar[], int n = 0); //默认构造函数;
        Sales();                       //用户自定义构造函数;
        void show_sales() const;
    };
}

#endif

//10.10 - 4(sales).cpp

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

namespace SALES
{
    
    
    Sales::Sales(double ar[], int n) //默认构造函数;
    {
    
    
        double total = 0.0;
        double max = ar[0];
        double min = ar[0];
        for (int i = 1; i < n; i++)
        {
    
    
            this->sales[i] = ar[i];
            total += ar[i];
            if (ar[i] > max)
            {
    
    
                max = ar[i];
            }
            if (ar[i] < min)
            {
    
    
                min = ar[i];
            }
        }
        this->min = min;
        this->max = max;
        this->average = total / n;
    }

    Sales::Sales()
    {
    
    
        using namespace std;
        int len;
        cout << "Enter the length of sales(<= 4 and > 0): ";
        while (!(cin >> len) || len > 4 || len <= 0)
        {
    
    
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number(<= 4 and > 0): ";
        }
        double *temp = new double[len];
        cout << "Please enter the sales:" << endl;
        for (int i = 0; i < len; i++)
        {
    
    
            cout << "Please enter the content #" << i + 1 << ": ";
            while (!(cin >> temp[i]))
            {
    
    
                cin.clear();
                while (cin.get() != '\n')
                    continue;
                cout << "Please enter a number: ";
            }
        }
        *this = Sales(temp, len); //调用默认构造函数赋值给调用对象;
        delete[] temp;
    }

    void Sales::show_sales() const
    {
    
    
        std::cout << "Sales average: " << this->average << std::endl;
        std::cout << "Sales max: " << this->max << std::endl;
        std::cout << "Sales min: " << this->min << std::endl;
        return;
    }
}

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

//--------------------------------------------------------------------
//10.10 - 5(main).cpp

#include <iostream>
#include <cctype>
#include "stack.h"

int main()
{
    
    
    using namespace std;
    char ch;
    Stack st;
    Item temp;
    double total = 0.0;

    cout << "a to add a customer." << endl;
    cout << "d to delete a customer." << endl;
    cout << "q to exit the menu." << endl;
    cout << "Please enter your choice: ";
    while (cin >> ch && tolower(ch) != 'q')
    {
    
    
        while (cin.get() != '\n')
            continue;
        if (tolower(ch) != 'a' && tolower(ch) != 'd') //处理错误选择;
        {
    
    
            cout << "Please enter a, d or q: ";
            continue;
        }
        switch (tolower(ch))
        {
    
    
        case 'a':
        {
    
    
            cout << "Enter the customer's fullname: ";
            cin.getline(temp.fullname, 35);
            cout << "Enter the customer's payment: ";
            while (!(cin >> temp.payment)) //处理错误非数值输入;
            {
    
    
                cin.clear();
                while (cin.get() != '\n')
                    continue;
                cout << "Please enter an number: ";
            }
            if (st.isfull())
            {
    
    
                cout << "Can't add new customer." << endl;
            }
            else
            {
    
    
                st.push(temp);
            }
            break;
        }
        case 'd':
        {
    
    
            if (st.isempty())
            {
    
    
                cout << "No any customer.\n";
            }
            else
            {
    
    
                st.pop(temp);
                total += temp.payment; //累计payment的数值;
                cout << "Customer " << temp.fullname << " will quit." << endl;
                cout << "Now the total payments are: " << total << endl; //报告当前total的总数;
            }
            break;
        }
        }
        cout << "\n\n\n";
        cout << "a to add a customer." << endl;
        cout << "d to delete a customer." << endl;
        cout << "q to exit the menu." << endl;
        cout << "Please enter your choice: ";
    }
    cout << "Bye." << endl;

    return 0;
}

//10.10 - 5(stack).h

#ifndef STACK_H_
#define STACK_H_

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

class Stack
{
    
    
private:
    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

//10.10 - 5(stack).cpp

#include "stack.h"

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

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

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

bool Stack::push(const Item &item)
{
    
    
    if (top < MAX)
    {
    
    
        items[top++] = item;
        return true;
    }
    else
    {
    
    
        return false;
    }
}

bool Stack::pop(Item &item)
{
    
    
    if (top > 0)
    {
    
    
        item = items[--top];
        return true;
    }
    else
    {
    
    
        return false;
    }
}

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

//--------------------------------------------------------------------
//10.10 - 6(main).cpp

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

int main()
{
    
    
    using std::cout;
    using std::endl;
    Move temp;

    cout << "Starting values:" << endl;
    temp.showmove();
    cout << "After x + 2, y + 5:" << endl;
    temp.reset(2, 5);
    temp.showmove();
    cout << "After adding new object value:" << endl;
    temp = temp.add(temp); //对象赋值;
    temp.showmove();

    return 0;
}

//10.10 - 6(move).h

#ifndef MOVE_H_
#define MOVE_H_

class Move
{
    
    
private:
    double x;
    double y;

public:
    Move(double a = 0.0, double b = 0.0);
    void showmove() const;
    Move add(const Move &m) const;
    void reset(double a = 0.0, double b = 0.0);
};

#endif

//10.10 - 6(move).cpp

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

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

void Move::showmove() const
{
    
    
    std::cout << "x = " << x << std::endl;
    std::cout << "y = " << y << std::endl;
    return;
}

Move Move::add(const Move &m) const
{
    
    
    Move temp;
    temp.x = m.x + this->x; //加上调用对象的x值;
    temp.y = m.y + this->y; //加上调用对象的y值;
    return temp;            //返回值为一个新对象;
}

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

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

//--------------------------------------------------------------------
//10.10 - 7(main).cpp

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

int main()
{
    
    
    using std::cout;
    using std::endl;
    Plorg temp;

    cout << "The starting plorg information:" << endl;
    temp.show_plorg();
    temp.create_new_plorg("Cloverx");
    cout << "\nAfter changing name and ci:" << endl;
    temp.show_plorg();
    temp.reset_ci();
    cout << "\nAfter changing ci:" << endl;
    temp.show_plorg();
    cout << "Bye." << endl;

    return 0;
}

//10.10 - 7(plorg).h

#ifndef PLORG_H_
#define PLORG_H_

class Plorg
{
    
    
private:
    char fullname[20];
    int ci;

public:
    Plorg(); //默认构造函数;
    void reset_ci();
    void show_plorg() const;
    void create_new_plorg(const char *newname);
};

#endif

//10.10 - 7(plorg).cpp

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

Plorg::Plorg()
{
    
    
    strcpy(fullname, "Plorga");
}

void Plorg::reset_ci()
{
    
    
    using std::cin;
    using std::cout;
    int my_ci;

    cout << "Please enter an new ci number: ";
    while (!(cin >> my_ci)) //修改CI;
    {
    
    
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "Please enter an number: ";
    }
    this->ci = my_ci;
    return;
}

void Plorg::show_plorg() const
{
    
    
    using std::cout;
    using std::endl;

    cout << "The plorg name is: " << this->fullname << endl;
    cout << "The plorg ci is: " << this->ci << endl;
    return;
}

void Plorg::create_new_plorg(const char *newname)
{
    
    
    strncpy(fullname, newname, 20); //新名称不超过20个字符;
    fullname[19] = '\0';
    this->ci = 50;
    return;
}

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

//--------------------------------------------------------------------
//10.10 - 8(main).cpp

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

void traverse(Item &item);

int main()
{
    
    
    using namespace std;
    char ch;
    Item temp;
    List mylist;

    cout << "The list include following functions:" << endl;
    cout << "a to add an number." << endl;
    cout << "v to visit every number." << endl;
    cout << "q to exit the menu." << endl;
    cout << "Please enter your choice: ";
    while (cin >> ch && tolower(ch) != 'q')
    {
    
    
        while (cin.get() != '\n')
            continue;
        if (tolower(ch) != 'a' && tolower(ch) != 'v') //处理错误选择;
        {
    
    
            cout << "Please enter a, v or q: ";
            continue;
        }
        switch (tolower(ch))
        {
    
    
        case 'a':
        {
    
    
            cout << "Please enter an number: ";
            while (!(cin >> temp)) //处理错误非数值输入;
            {
    
    
                cin.clear();
                while (cin.get() != '\n')
                    continue;
                cout << "Please enter an number again: ";
            }
            if (mylist.is_full())
            {
    
    
                cout << "The list is full. Can't add new number." << endl;
            }
            else
            {
    
    
                mylist.add_data(temp);
                cout << "Add number " << temp << " successfully." << endl;
            }
            break;
        }
        case 'v':
        {
    
    
            if (mylist.is_empty())
            {
    
    
                cout << "No number.\n";
            }
            else
            {
    
    
                cout << "Visit every number:" << endl;
                mylist.visit(traverse);
            }
            break;
        }
        }
        cout << "\n\n\n";
        cout << "The list include following functions:" << endl;
        cout << "a to add an number." << endl;
        cout << "v to visit every number." << endl;
        cout << "q to exit the menu." << endl;
        cout << "Please enter your choice: ";
    }
    cout << "Bye." << endl;

    return 0;
}

void traverse(Item &item)
{
    
    
    std::cout << item << ' ';
    return;
}

//10.10 - 8(list).h

#ifndef LIST_H_
#define LIST_H_

typedef int Item;

class List
{
    
    
private:
    static const int MAX = 10;
    Item items[MAX];
    int index;

public:
    List();
    void add_data(Item item);
    bool is_empty();
    bool is_full();
    void visit(void (*pf)(Item &));
};

#endif

//10.10 - 8(list).cpp

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

List::List()
{
    
    
    this->index = 0;
}

void List::add_data(Item item)
{
    
    
    this->items[index++] = item;
    return;
}

bool List::is_empty()
{
    
    
    return 0 == index;
}

bool List::is_full()
{
    
    
    return MAX == index;
}

void List::visit(void (*pf)(Item &))
{
    
    
    for (int i = 0; i < this->index; i++)
    {
    
    
        (*pf)(this->items[i]);
    }
    return;
}

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

//------------------------------------------2020年10月17日 ----------------------------------------------;

猜你喜欢

转载自blog.csdn.net/m0_46181359/article/details/109134043
今日推荐