C++ Primer Plus, Chapter10对象和类,excercise

1.银行账户类,存款、取款

这里写图片描述
这里写图片描述

//account.h
#include <string>
#ifndef ACCOUNT_H_
#define ACCOUNT_H_
class Account
{
private:
    std::string name;
    std::string acctnum;
    double balance;
public:
    Account (const std::string &client, const std::string &num, double bal = 0.0);//构造函数
    void show() const;
    void deposit(double cash);
    void withdraw(double cash);
};
#endif

//account.cpp
#include "stdafx.h";
#include "account.h"
#include <iostream>

Account::Account(const std::string &client, const std::string &num, double bal)
{
    name = client;
    acctnum = num;
    balance = bal;
}
void Account::show() const
{
    std::cout << "name: " << name << ", acctnum: " << acctnum << ", balance: " << balance << "\n";
}
void Account::deposit(double cash)
{
    if (cash < 0)
        std::cout << "The cash you deposit can't be negative; Transaction is aborted.\n";
    else
        balance += cash;
}
void Account::withdraw(double cash)
{
    if (cash < 0)
        std::cout << "The cash you withdraw can't be negative; Transaction is aborted.\n";
    else if (cash > balance)
        std::cout << "You don't have more than $" << balance << "; Transaction is aborted.\n";
    else
        balance -= cash;
}

//main.cpp
#include "stdafx.h"
#include "account.h"
#include <iostream>

int main()
{
    Account wei = Account("wei lj", "123456", 1100.0);
    wei.show();
    std::cout << "After depositing $500:\n";
    wei.deposit(500.0);
    wei.show();
    std::cout << "After withdrawing $2000:\n";
    wei.withdraw(2000.0);
    wei.show();
    std::cout << "After withdrawing $1500:\n";
    wei.withdraw (1500.0);
    wei.show();
    std::cin.get();
    return 0;
}

2.string对象和char数组存储姓名

这里写图片描述
这里写图片描述

//string对象和char数组的定义,作为参数,赋值的区别
//person.h
#include <string>
#ifndef PERSON_H_
#define PERSON_H_
class Person
{
private:
    static const int LIMIT = 25;
    std::string lname;
    char fname[LIMIT];
public:
    Person()
    {
        lname = "";
        fname[0] = '\0';
    }
    Person(const std::string &ln, const char * fn = "Heyyou");
    void show() const;
    void FormalShow() const;
};
#endif

//person.cpp
#include "stdafx.h"
#include "person.h"
#include <iostream>

Person::Person(const std::string &ln, const char *fn)
{
    lname = ln;
    strcpy(fname, fn);
}
void Person::show() const
{
    std::cout << fname << " " << lname << "\n";
}
void Person::FormalShow() const
{
    std::cout << lname << ", " << fname << "\n";
}

//main.cpp
#include "stdafx.h"
#include "person.h"
#include <iostream>

int main()
{
    Person one;
    Person two("Smythecraft");
    Person three = Person("Dimwiddy", "Sam");
    one.show();
    two.show();
    two.FormalShow();
    three.show();
    three.FormalShow();
    std::cin.get();
    return 0;
}

3.Golf类,用构造函数实现setgolf()方法的交互

这里写图片描述

//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 = "zhang san", int hc = 20);  //默认构造函数
    int setgolf();
    void reset_hc(int hc);
    void showgolf() const;
};
#endif

//golf.cpp
#include "stdafx.h"
#include "golf.h"
#include <iostream>

Golf ::Golf(const char *name, int hc)
{
    strcpy(fullname, name);
    handicap = hc;
}
int Golf::setgolf()
{
    char name[Len];
    int hc;
    std::cout << "Enter the fullname: ";
    std::cin.getline(name, Len);
    if (name[0] == '\0') //双等号!!
        return 0;
    else
    {
        std::cout << "Enter the handicap: ";
        std::cin >> hc;
        std::cin.get();
        *this = Golf(name, hc); //*this = 是必需的
        return 1;
    }
}
void Golf::reset_hc(int hc)
{
    handicap = hc;
}
void Golf::showgolf() const
{
    std::cout << fullname << ": " << handicap << std::endl;
}

//main.cpp
#include "stdafx.h"
#include <iostream>
#include "golf.h"
#include <ctime>
int main()
{
    using namespace std;
    Golf gf[5];
    int i;
    for (i = 0; i < 5; i++)
    {
        int n = gf[i].setgolf();
        if (n == 0) //双等号!!
            break;
        else
            //setgolf(gf[i]);
            continue;
    }
    cout << i << endl;
    cout << "Reset handicap to new value:\n";
    for (int j = 0; j < i; j++)
    {
        int hc;
        cout << "Enter the new handicap: ";
        cin >> hc;
        gf[j].reset_hc(hc);
    }
    cout << "Display contents of golf structure:\n";
    for (int j = 0; j < i; j++)
        gf[j].showgolf();//j写成了i,要认真!
    clock_t delay = 10 * CLOCKS_PER_SEC;
    clock_t start = clock();
    while (clock() - start < delay)
        ;
    return 0;
}

4.Sales类,用构造函数实现setsales()方法的交互、名称空间

这里写图片描述

//namespace.h
#ifndef NAMESPACE_H_
#define NAMESPACE_H_
namespace SALES
{
    class Sales
    {
    private:
        static const int QUARTERS = 4;
        double sales[QUARTERS];
        double average;
        double max;
        double min;
    public:
        Sales(const double *ar, int n); //因为不会写数组的默认参数值,所以不是默认构造函数
        void setsales();
        void showsales() const;
    };
}
#endif

//namespace.cpp
#include "stdafx.h"
#include "namespace.h"
#include <iostream>


namespace SALES
{
    Sales::Sales(const double *ar, int n)
    {
        int i;
        for (i = 0; i < n; i++)
            sales[i] = ar[i];
        for (int j = i; j < n; j ++)
            sales[j] = 0;
        double sum = 0;
        for (int j = 0; j < QUARTERS; j++)
            sum += sales[j];
        average = sum / QUARTERS;
        double max1 = sales[0];
        for (int j = 1; j < QUARTERS; j++)
        {
            if (sales[j] > max1)
                max1 = sales[j];
        }
        max = max1;
        double min1 = sales[0];
        for (int j = 1; j < QUARTERS; j++)
        {
            if (sales[j] < min1)
                min1 = sales[j];
        }
        min = min1;
    }
    void Sales::setsales()
    {
        double ar[QUARTERS];
        int i = 0;
        std::cout << "Enter a sale: ";
        while (std::cin >> ar[i])
        {
            i++;
            if (i < QUARTERS)
                std::cout << "Enter a sale (q to quit): ";
            else
                break;
        }
        *this = Sales(ar, i); //!!!!!! *this = 必须要,没有的话设置的值不能传递给调用该方法的对象
    }
    void Sales::showsales() const
    {
        for (int i = 0; i < QUARTERS; i++)
        {
            std::cout << "sales: " << 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;
    }
}

//mian.cpp
#include "stdafx.h"
#include <iostream>
#include "namespace.h"
#include <ctime>

using namespace SALES;
int main()
{
    using namespace std;
    double ar[4] = {1.1, 1.2, 1.3, 1.4};
    Sales s1 = Sales(ar, 4); //先用构造函数显式初始化,不能不显式初始化,非交互式
    Sales s2 = Sales(ar, 4);
    s2.setsales();
    cout << "Display s1:\n";
    s1.showsales(); //重新设置s2的值,交互式
    cout << "Display s2:\n";
    s2.showsales();
    clock_t delay = 10 * CLOCKS_PER_SEC;
    clock_t start = clock();
    while (clock() - start < delay)
        ;
    return 0;
}

5.从栈中添加和删除customer结构

这里写图片描述

//stack.h
#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;
public:
    Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);
};
#endif

//stack.cpp
#include "stdafx.h"
#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;  //一开始top还是原来的数,执行完本句之后才+1
        return true;
    }
    else
        return false;
}
bool Stack::pop(Item &item)
{
    if (top > 0)
    {
        item = items[--top]; //top为个数,比数组最大索引大1,因此先要-1
        return true;
    }
    else
        return false;
}

//main.cpp
int main()
{
    using namespace std;
    Stack st;
    char ch;
    Item po;
    cout << "Please enter A to add a purchase order,\n"
         << "p to process a PO, or Q to quit.\n";
    double total = 0;
    while (cin >> ch && toupper(ch) != 'Q')
    {
        while (cin.get() != '\n')
            continue;
        if (!isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch(ch)
        {
        case 'A':
        case 'a':
            cout << "Enter the fullname of the customer: ";
            cin.getline(po.fullname, 35);
            cout << "Enter the payment: ";
            cin >> po.payment;
            if (st.isfull())
                cout << "stack already full\n";
            else 
                st.push(po);
            break;
        case 'P':
        case 'p':
            if (st.isempty())
                cout << "stack already empty\n";
            else
            {
                st.pop(po);
                total += po.payment;
                cout << "PO #" << po.fullname << ": " << po.payment << " popped, total $" << total << " popped\n";
            }
            break;
        }
        cout << "Please enter A to add a purchase order,\n"
             << "p to process a PO, or Q to quit.\n";
    }
    cout << "Bye!\n";
    cin.get();
    return 0;
}

6.Move类

这里写图片描述

//move.h
#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 add(const Move &m) const;
    void reset(double a = 0, double b = 0);
};
#endif

//move.cpp
#include "stdafx.h"
#include "move.h"
#include <iostream>

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 mm;
    mm.x = this->x + m.x; //this !!!
    mm.y = this->y + m.y;
    return mm;
}
void Move::reset(double a, double b)
{
    x = a;
    y = b;
}

//main.cpp
#include "stdafx.h"
#include "move.h"
#include <iostream>

int main()
{
    Move m1 = Move(2.0, 2.0);
    Move m2 = Move(1.0, 1.0);
    Move m3;
    std::cout << "#m1\n";
    m1.showmove();
    std::cout << "#m2\n";
    m2.showmove();
    std::cout << "#m3\n";
    m3.showmove();
    std::cout << "After add(), m3 = m1 + m2,show m3\n";
    m3 = m1.add(m2);
    m3.showmove();
    std::cout << "After reset(),show m3\n";
    m3.reset(5.0,5.0);
    m3.showmove();
    std::cin.get();
    return 0;
}

7.Plorg类

这里写图片描述
这里写图片描述

//plorg.h
#ifndef PLORG_H_
#define PLORG_H_
class Plorg
{
private:
    char name[20];
    int CI;
public:
    Plorg(const char *n = "Plorga", const int ci = 50);
    void reset_ci(int ci);
    void show() const;
};
#endif

//plorg.cpp
#include "stdafx.h"
#include "plorg.h"
#include <iostream>

Plorg::Plorg(const char *n, int ci)
{
    strcpy(name, n);
    CI = ci;
}
void Plorg::reset_ci(int ci)
{
    CI = ci;
}
void Plorg::show() const
{
    std::cout << name << ": " << CI << "\n";
}

//main.cpp
#include "stdafx.h"
#include "plorg.h"
#include <iostream>

int main()
{
    Plorg pl1;
    Plorg pl2 = Plorg("zhangsan", 55);
    std::cout << "show pl1, pl2\n";
    pl1.show();
    pl2.show();
    std::cout << "reset the CI in pl1\n";
    pl1.reset_ci(20);
    pl1.show();
    std::cin.get();
    return 0;
}

8.列表(用类实现)、指针函数

这里写图片描述

//重点::指针函数的写法
//list.h
#ifndef LIST_H_
#define LIST_H_
typedef int Item;
const int MAX = 10;
class List
{
private:
    int top;
    Item items[MAX];
public:
    List();
    bool add(const Item & item);
    bool isempty() const;
    bool isfull() const;
    void visit(void (*pf)(Item & item)); //直接这么写
};
#endif

list.cpp
#include "stdafx.h"
#include "list.h"

List::List()
{
    top = 0;
}
bool List::add(const Item & item)
{
    if (top < MAX)
    {
        items[top++] = item; //top为个数
        return true;
    }
    else
        return false;
}
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]); //调用指针函数
}

//main.cpp
#include "stdafx.h"
#include "list.h"
#include <iostream>
#include <ctime>

void print(Item & item); //指针函数原型
int main()
{
    using namespace std;
    List l;
    int n;
    cout << "Enter an item: ";
    while (cin >> n)
    {
        if (l.isfull())
        {
            cout << "the list already full.\n";
            break;
        }   
        else
        {
            l.add(n);
            cout << "Enter an item (q to quit): ";
        }   
    }
    void (*pf)(Item &item); //声明函数指针
    pf = print; //赋地址
    l.visit((*pf)); //调用成员函数visit()
    clock_t delay = 10 * CLOCKS_PER_SEC;
    clock_t start = clock();
    while (clock() - start < delay)
        ;
    cin.get();
    cin.get();
    return 0;
}
void print(Item & item) //指针函数的原函数的定义
{
    std::cout << item << "\n"; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值