C++ Primer Plus 第10章 课后编程练习 代码

第一题
// 1.头文件
//定义类 bank
#ifndef BANK_H_
#define BANK_H_
#include <string>
class Bank
{
private:
    std::string name;
    std::string account;
    double money;

public:
    //创建对象并且初始化,默认构造函数
    Bank();
    // 默认初始化
    Bank(const std::string &name_, const std::string &account_, unsigned long money_ = 0);
    // 显示账户信息
    void show() const;
    // 存入参数指定的存款
    bool savemoney(double money_);
    // 取出参数指定的款项
    bool withdraw(double money_);
    ~Bank();
};

// 2.函数定义
// 给出类方法的实现
#include "bank.h"
#include <iostream>

Bank::Bank()
{
    name = "no name";
    account = "no account";
    money = 0;
}

Bank::Bank(const std::string &name_, const std::string &account_, unsigned long money_)
{
    name = name_;
    account = account_;
    money = money_;
}

void Bank::show() const
{
    std::cout << "Name: " << name << std::endl;
    std::cout << "Account: " << account << "\t"
              << "Money: " << money << std::endl;
}

bool Bank::savemoney(double money_)
{
    if (money_ <= 0)
    {
        std::cout << "Check your argument of money!\n";

        return false;
    }
    else
    {
        money += money_;
        return true;
    }
}

bool Bank::withdraw(double money_)
{
    if (money_ > money || money_ <= 0)
    {
        std::cout << "Sorry, your credit is running low.\n";
        return false;
    }
    else
    {
        money -= money_;
        return true;
    }
}

Bank::~Bank()
{
}
#endif

// 3.主函数
#include "bank.h"
#include <iostream>

int main()
{
    Bank Dong;
    Dong.show();
    Bank Lv{"Lv Qingyuan", "1234567890", 10000};
    Lv.show();

    Dong.savemoney(1000.0);
    Lv.savemoney(5000.0);
    Dong.show();
    Lv.show();

    Dong.withdraw(500.0);
    Dong.show();

    return 0;
}
第二题
// 1.头文件
#ifndef PERSON_H_
#define PERSON_H_
#include <iostream>
#include <string>

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

public:
    Person()
    {
        lname = "";
        fname[0] = '\0';
        // !将字符数组的第一个元素设置为空字符表示结尾,但还是那个疑问?为什么fname不可以接受字符串常量呢(如17行)?
        // !字符串之间是不可以相互赋值的,如果想拷贝某字符串给另一字符串,只能strcpy!!
    }
    Person(const std::string &ln, const char *fn = "Heyyou");
    void Show() const;
    void FormalShow() const;
    ~Person();
};

#endif

// 2.函数定义
#include "Person.h"
#include <cstring>
#include <iostream>
Person::Person(const std::string &ln, const char *fn)
{
    lname = ln;
    std::strcpy(fname, fn);
}

void Person::Show() const
{
    std::cout << fname << " " << lname << std::endl;
}
void Person::FormalShow() const
{
    std::cout << lname << "," << fname << std::endl;
}
Person::~Person()
{
}

// 3.主函数
#include "Person.h"
#include <iostream>

int main()
{
    Person one;
    Person two("Smythecraft");
    Person three("Dimwiddy", "Sam");

    one.Show();
    one.FormalShow();
    two.Show();
    two.FormalShow();
    three.Show();
    three.FormalShow();
    return 0;
}
3// 1.头文件
#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 handi);
    int setgolf();
    void re_handicap(int hc);
    void showgolf() const;
    ~Golf();
};

#endif

// 2.函数定义
#include "golf.h"
#include <cstring>
#include <iostream>
Golf::Golf()
{
    fullname[0] = '\0';
    handicap = 0;
}
//功能:通过成员函数参数,初始化Golf类对象
//参数:指向字符的指针、int
//返回:无
Golf::Golf(const char *name, int handi)
{
    std::strcpy(fullname, name);
    handicap = handi;
}
//功能:通过用户输入,来设置调用该函数的Golf类对象
//参数: 无
// 返回:成功则返回1,失败则返回0
int Golf::setgolf()
{
    using std::cin;
    using std::cout;
    char temp_n[Len];
    int temp_h;

    cout << "Enter the fullname\n";
    cin.get(temp_n, Len);
    char ch = cin.get(); // 如果输入字符串数目超限,那么会读取到非'\n'; 如果输入字符串数目没有超限, 那么会读取'\n'

    if (cin.good() && temp_n[0] != '\0' && ch == '\n') //表示名字读取正常,并且字符串数目未超过限制数目
    {
        cout << "Enter the handicap:\n";
        cin >> temp_h;
        cin.get();

        *this = Golf(temp_n, temp_h);
        return 1; //返回1,表示成功设置一个Golf类对象
    }

    //注意:读取失败并且返回0的原因有很多,如上述if语句的测试条件
    if (cin.eof())
    {
        cout << "cin-fullname failed due to EOF.\n";
    }
    else if (cin.fail())
    {
        cout << "cin-fullname failed due to TypeMismatched.\n";
    }
    else if (fullname[0] == '\0')
    {
        cout << "QUIT.\n";
    }
    else if (ch != '\n')
    {
        cout << "cin-fullname failed due to Input String Too Long.\n";
        while (cin.get() != '\n')
        {
            continue;
        }
    }

    return 0;
}
// 功能:重新设置handicap的值
// 参数:int
// 返回:无
void Golf::re_handicap(int hc)
{
    handicap = hc;
}
// 功能:显示类对象Golf的成员
// 参数:常量结构引用
// 返回:无
void Golf::showgolf() const
{
    using std::cout;
    using std::endl;
    cout << "Name: " << fullname
         << "  Handicap: " << handicap << endl;
}

Golf::~Golf()
{
}

// 3.主函数
#include "golf.h"
#include <iostream>
int exi = 1;
int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    cout << "How many information do you want to input?\n";
    int many;
    cin >> many;
    many++;

    if (many > 0)
    {
        Golf array[many];
        cin.get();
        array[0] = Golf("DongZhaoCheng", 120); //调用构造函数,初始化对象数组的一个对象
        cout << "Now, the array has one member!\n";
        cout << endl;

        while (exi < many && array[exi].setgolf()) //exi = 1是具有外部链接性的全局变量
        {
            ++exi;
        }
        cout << endl;

        cout << "You can display the info by choicing #: (1 ~ " << exi << "):" << endl;
        int j;
        cin >> j;
        while (j < 1 || j > exi)
        {
            cout << "Sorry,check and input again:\n";
            cin >> j;
        }
        array[j - 1].showgolf();
        cout << endl;

        cout << "You can modify the handicap in the array of golf, " << endl
             << "Please input the index: (1 ~ " << exi << "):\n";
        cin >> j;
        while (j < 1 || j > exi)
        {
            cout << "Sorry,check and input again:\n";
            cin >> j;
        }
        cout << "Ok!,Please enter the modified value:\n";
        int temp;
        cin >> temp;
        array[j - 1].re_handicap(temp);

        cout << "Modify Success:\n";
        array[j - 1].showgolf();
    }
    else
    {
        cout << "Your enter is wrong!\n";
    }

    cout << "BYEBYE!!!\n";
    return 0;
}
第四题
// 1.头文件
namespace SALES
{
    const double c_d4[7] = {34.44, 56.66, 33.33, 56.45, 98.99, 67.33, 56.44};
    class Sales
    {
    private:
        static const int QUARTERS = 4;
        double sales[QUARTERS];
        double average;
        double max;
        double min;

    public:
        // 默认构造函数
        Sales();
        // 功能:使用参数列表中的参数,设创建并初始化类对象的值,找出数组中较小的4个元素赋给类数据成员sales
        // 然后计算出min、max、average
        // double数据数组、数组的项数int n
        // 返回:无
        Sales(const double ar[], int n);
        ~Sales();

        // 功能:设置调用对象的值
        void setSales();
        // 功能:显示调用对象的成员
        void showSales() const;
    };
} // namespace SALES

// 2.函数定义
#include "class.h"
#include <cstdlib>
#include <iostream>

namespace SALES
{
    Sales::Sales(const double ar[], int n)
    {
        int mycomp(const void *p1, const void *p2);
        double copyar[n];
        for (int i = 0; i < n; i++)
        {
            copyar[i] = ar[i];
        }
        qsort(copyar, n, sizeof(double), mycomp);
        for (int i = 0; i < 4; i++)
        {
            sales[i] = copyar[i];
        }
        max = sales[3];
        min = sales[0];

        double total = 0;
        for (int i = 0; i < 4; i++)
        {
            total += sales[i];
        }
        average = total / 4;
    }

    // 通过与用户交互,设置调用对象的值
    void Sales::setSales()
    {
        int mycomp(const void *p1, const void *p2);

        std::cout << std::endl;
        std::cout << "How many number will you enter?\n";
        int n;
        std::cin >> n;
        double arrar_input[n];

        std::cout << "Starting enter(1th number):\n";
        int i = 0;
        while (i < n && std::cin >> arrar_input[i]) //这里写的有点简陋了,哎呀急着买菜做饭去呢
        {
            i++;
            if (i < n)
                std::cout << "Enter next number:\n";
        }
        *this = Sales(arrar_input, n);
    }

    void Sales::showSales() const
    {
        std::cout.precision(4);
        std::cout << "sales array:\t";
        for (int i = 0; i < 4; i++)
        {
            std::cout << sales[i] << "\t";
        }
        std::cout << std::endl;

        std::cout << "Average: " << average << std::endl;
        std::cout << "Max: " << max << std::endl;
        std::cout << "Min: " << min << std::endl;
    }

    int mycomp(const void *p1, const void *p2)
    {
        int ret = 0;
        const double *a1 = (const double *)p1;
        const double *a2 = (const double *)p2;
        if (*a1 > *a2)
        {
            ret = 1;
        }
        else if (*a1 < *a2)
        {
            ret = -1;
        }
        else
        {
            ret = ret;
        }
        return ret;
    }
    Sales::Sales()
    {
        for (int i = 0; i < QUARTERS; i++)
            sales[i] = 0;
        average = 0;
        max = 0;
        min = 0;
    }
    Sales::~Sales()
    {
    }
} // namespace SALES

// 3.主函数
#include "class.h"
#include <cstdlib>
#include <iostream>
int main()
{
    using namespace SALES;
    Sales s1;            //使用默认构造函数
    s1 = Sales(c_d4, 7); //通过自定义的构造函数创建临时对象,并赋值给s1
    Sales s2;
    s1.showSales();
    std::cout << "**********************************\n";
    s2.setSales(); //通过和用户交互来实现设置对象
    s2.showSales();
}
第五题
// 1.头文件
#ifndef STACK_H_
#define STACK_H_

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

typedef customer Item;

class Stack
{
private:
    enum
    {
        MAX = 10
    };
    Item items[MAX];
    int top; //top的值代表栈顶的序号

public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);
};

#endif

// 2.函数定义
// 类成员函数的定义
#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 (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;
}

// 3.主函数
#include "stack.h"
#include <cctype>
#include <iostream>

int main()
{
    using namespace std;
    Stack st; //定义了一个类对象
    char ch;
    customer po;
    double tot_payment = 0;
    cout << "Please enter A to add a customer-info order,\n"
         << "P to pop a customer-info,Q to quit.\n";

    while (cin >> ch && toupper(ch) != 'Q')
    {
        while (cin.get() != '\n') //清除每行后续不需要的字符
        {
            continue;
        }
        if (!isalpha(ch))
        {
            cout << "Check your input!!!\n";
            continue;
        }
        switch (ch)
        {
        case 'a':
        case 'A':
            if (st.isfull())
            {
                cout << "Stack is full\n";
            }
            else
            {
                cout << "Enter a customer's name(< 35 chars):";
                cin.getline(po.fullname, 35);
                cout << "Enter the customer's payment:";
                cin >> po.payment;
                st.push(po);
            }
            break;
        case 'p':
        case 'P':
            if (st.isempty())
            {
                cout << "Sorry.Stack is empty\n";
            }
            else
            {
                st.pop(po); //将栈顶元素弹出,放在变量po中
                tot_payment += po.payment;
                cout << "The tot_payment is " << tot_payment << endl;
            }
            break;
        }
        cout << "Please enter A to add a customer-info order,\n"
             << "P to pop a customer-info,Q to quit.\n";
    }
    cout << "Bye\n";

    return 0;
}

第六题
// 1.头文件
#ifndef MOVE_H_
#define MOVE_H_

class Move
{
private:
    double x;
    double y;

public:
    Move(double a = 0, double b = 0);
    void showmove() const;
    // 函数返回值是Move类对象
    // 此函数将m的x与调用对象的x相加,以获得新的x;y同理
    // 创建一个新的对象,初始化为x和y的值,并返回它
    Move add(const Move &m) const;

    void reset(double a = 0, double b = 0); // 将x和y重置为a和b的值
};
#endif

// 2.函数定义
#include "move.h"
#include <iostream>
Move::Move(double a, double b)
{
    x = a;
    y = b;
}

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

Move Move::add(const Move &m) const
{
    Move n_object;
    n_object.x = m.x + x;
    n_object.y = m.y + y;

    return n_object;
}

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

// 3.主函数
#include "move.h"
#include <iostream>

int main()
{
    Move obj;
    obj.showmove();

    obj = Move(4.8, 9.1);
    obj.showmove();

    Move obj2 = obj.add(obj);
    obj2.showmove();

    obj.reset();
    obj.showmove();

    obj2.reset();
    obj2.showmove();

    return 0;
}
第七题
// 1.头文件
#ifndef PLORGA_H_
#define PLORGA_H_

class Plorg
{
private:
    enum
    {
        SIZE = 20
    };
    char name[SIZE];
    int CI;

public:
    // 此举是为了消除警告:ISO C++ forbids converting a string constant to 'char*'
    Plorg(char *n = (char *)"Plorga", int ci = 50);
    void ModCi(const int ci);
    void ShowPlorg() const;
};

#endif

// 2.函数定义
#include "plorga.h"
#include <cstring>
#include <iostream>

Plorg::Plorg(char *n, int ci)
{
    strcpy(name, n);
    CI = ci;
}

void Plorg::ModCi(const int ci)
{
    CI = ci;
}

void Plorg::ShowPlorg() const
{
    std::cout << "Name: " << name << std::endl;
    std::cout << "CI: " << CI << std::endl;
}

// 3.主函数
#include "plorga.h"
#include <iostream>

int main()
{
    Plorg obj1;
    obj1.ShowPlorg();

    // 此举是为了消除警告:ISO C++ forbids converting a string constant to 'char*'
    char *s = (char *)"Snail Dong";
    obj1 = Plorg(s, 10000);
    obj1.ShowPlorg();

    obj1.ModCi(9999);
    obj1.ShowPlorg();

    return 0;
}
第八题
// 1.头文件
#ifndef LIST_H_
#define LIST_H_

typedef double Item; // 暂定以double类型的数据作为Item

class List
{
private:
    enum
    {
        MAX = 10
    };
    Item items[MAX];
    int top; //用来描述列表中有几个成员

public:
    List();
    void AddItem(const Item &);
    bool IsEmpty() const;
    bool IsFull() const;
    void Visit(void (*pf)(Item &));
    void ShowList() const;
};
#endif

// 2.函数定义
#include "listt.h"
#include <iostream>

List::List()
{
    for (int i = 0; i < MAX; i++)
    {
        items[i] = 0;
    }
    top = 0;
}

void List::AddItem(const Item &item)
{
    if (IsFull())
    {
        std::cout << "The list is full\n";
    }
    else
    {
        items[top++] = item;
    }
}

bool List::IsEmpty() const
{
    return top == 0;
}

bool List::IsFull() const
{
    return top == MAX;
}
void List::Visit(void (*pf)(Item &item))
{
    for (int i = 0; i < top; i++)
    {
        pf(items[i]);
    }
}

void List::ShowList() const
{
    if (IsEmpty())
    {
        std::cout << "The list is empty!\n";
    }
    else
    {
        std::cout << "#:\t";
        for (int i = 0; i < top; i++)
        {
            std::cout << i + 1 << "\t";
        }
        std::cout << "\n";

        std::cout.precision(3);
        std::cout << "Con:\t";
        for (int i = 0; i < top; i++)
        {
            std::cout << items[i] << "\t";
        }
        std::cout << "\n";
    }
}

// 3.主函数
#include <iostream>
#include "listt.h"
#include <cmath>

void sqrt_(Item &item);
void Add_1(Item &item);

int main()
{
    List obj1; // 测试函数List().
    obj1.ShowList(); // 测试函数Isempty().

    obj1.AddItem(12.3);
    obj1.ShowList();
    for (int i = 0; i < 9; i++)
    {
        obj1.AddItem(i+2.5);
    }
    obj1.AddItem(5);//体现函数IsFull().
    obj1.ShowList();

    obj1.Visit(sqrt_);
    std::cout<<"After Calling function of sqrt_.\n";
    obj1.ShowList();

    obj1.Visit(Add_1);
    std::cout<<"After Calling function of Add_1.\n";
    obj1.ShowList();
    
    return 0;
}

// 求得每一项的平方根
void sqrt_(Item &item)
{
    item = sqrt(item);
}

void Add_1(Item &item)
{
    ++item;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咖啡与乌龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值