C++ primer plus第十章编程练习答案

1.为复习题 5 描述的类提供方法定义,并编写一个小程序来演示所有的特性

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

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

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

2.下面是一个非常简单的类定义:

class-Person
private:
static const LIMIT - 25;
sting lname;// Person'g last name
char fname [LIMIT], // Person"s first name

public:
Person{}(Iname =""; fname[0] =  '\0';}//#1

Person(const string   ln,const char * fn = "Heyyou"): // #2
// the following methods display lname and fname

void Show()const ;// firatname lastname format

void FormalShow() const; // lastnamefiratname format

它使用了一个 string 对象和一个字符数组,让您能够比较它们的用法。请提供未定义的方法的代码,以完成这个类的实现。再编写一个使用这个类的程序,它使用了三种可能的构造函数调用(没有参数、一个参数和两个参数》以及两种显示方法。下面是--个使用这些构造雨数和方法的例子:
Person one;// use default constructor

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

Person three("Dimwiddy","Sam");// use #2,no defaults
one .Show() ;
cout << endl:
one ,FormalShow ():
// etc.for two and three

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

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

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

    return 0;
}
#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
#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).";
}

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


3.完成第9章的编程练习1但要用正确的olf类声明替换那里的代码。用带合适参数的构造函数替换setgolf (golf&const char*int)以提供初始值。保setgolf )的交互版本但要用构造函数来实现它(例如,setgol)的代码应该获得数据,将数据传递给构造函数来创建一个临时对象,并将其赋给调用对象即*this)。

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

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

    Golf temp1;
    Golf temp2("MZZDX", 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;
}
#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
#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;
}

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

4.完成第9章的编程练习4,但将 Sales结构及相关的函数转换为一个类及其方法。用构造函数替换setSales(sales &,double[]int)函数。用构造函数实现 sctSales-(Sales &)方法的交互版本。将类保在名称空间SALES中。

#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;
}
#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
#include <iostream>
#include "sales.h"

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

5.考虑下面的结构声明:
struct customer
char fuFlname[35],
double payment;
编写一个程序,它从栈中添加和删除 customer 结构( 用 Sack 类声明表示)每次customer 结构被删除时,其 payment 的值都被加入到总数中,并报告总数。注意:应该可以直接使用 Stack 类而不作修改:只需修改 typedef声明,使Item 的类型为 customer,而不是unsigned long 即可。

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

6.下面是一个类声明:

class Move
private:
double x;
doubleyi
public:
Moveldoublea=0,double b= 0);// sets x,y toa,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

请提供成员函数的定义和测试这个类的程序。

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

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

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

7.Betelgeusean plorg 有这些特征。
数据:
plorg的名称不超过19个字符:
plorg有满意指数(CI),这是一个整数。
操作:
新的plorg将有名称,其CI值为50:
plorg的CI可以修改:

-plorg 可以报告其名称和CI:
plorg的默认名称为“Plorga”
请编写一个Plorg 类声明(包括数据成员和成员函数原型)来表示 porg,并编写成员函数的函数定义。
然后编写一个小程序;以演示 Plorg类的所有特性。

#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("MZZDX");
    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;
}
#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
#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))
    {
        cin.clear();
        while (cin.get() != '\n')
            continue;
        cout << "Please enter an number: ";
    }
    this->ci = my_ci;
}

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

void Plorg::create_new_plorg(const char *newname)
{
    strncpy(fullname, newname, 19);
    fullname[19] = '\0';
    this->ci = 50;
}


8.可以将简单列表描述成下面这样:
可存储0或多个某种类型的列表;
可创建空列表;
可在列表中添加数据项
可确定列表是否为空:
可确定列表是否为满;可访问列表中的每一个数据项,并对它执行某种操作。可以看到,这个列表确实很简单,例如,它不允许插入或删除数据项。请设诈一个 List 类来表示这种抽象类型。您应提供头文件 listh和实现文件 listcpp,前者包含类定义后者包含类方法的实现。您还应创建一个简短的程序来使用这个类。
该列表的规范很简单,这主要旨在简化这个编程练习。可以选择使用数组或链表来实现该列表,但公有接口不应依赖于所做的选择。也就是说,公有接口不应有数组索引、节点指针等。应使用通用概念来表达创建列表、在列表中添加数据项等操作。对于访问数据项以及执行操作,通常应使用将函数指针作为参数的函数来处理:
void visit(void /pf)(Item &)l;
其中,pf指向一个将 ltem引用作为参数的函数(不是成员函数)tem 是列表中数据项的类型。visit()函数将该函数用于列表中的每个数据项。

#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 << ' ';
}
#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
#include <iostream>
#include "list.h"

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

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值