c++ primer plus第六版第十二章编程练习

  1. 根据下面类声明提供方法实现和使用成员函数的小程序。
    (看到这个类名字和成员一度懵逼,不知道要实现什么需求,腹诽:牛?hobby?不明觉厉)
    声明头文件
#include <iostream>
class Cow
{
private:
    char name[20];
    char *hobby;
    double weight;

public:
    Cow();
    Cow(const char *nm, const char *ho, double wt);
    Cow(const Cow &c);
    ~Cow();
    Cow &operator=(const Cow &c);
    void showcow() const;
};

方法实现

#include "cow.h"
using std::cout;
using std::endl;
#include <cstring>
Cow::Cow()
{
    strcpy(name, "BalaBala");
    hobby = new char[6];
    strcpy(hobby, "grazing");
    weight = 0.0;
} //default constructor
Cow::Cow(const char *nm, const char *ho, double wt)
{
    strcpy(name, nm);
    hobby = new char[strlen(ho) + 1];
    strcpy(hobby, ho);
    weight = wt;
} //constructor
Cow::Cow(const Cow &c)
{
    strcpy(name, c.name);
    hobby = new char[strlen(c.hobby) + 1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
} //copy constructor
Cow::~Cow()
{
    delete[] hobby;
}
Cow &Cow::operator=(const Cow &c)
{
    if (this == &c)
        return *this;
    strcpy(name, c.name);
    hobby = new char[strlen(c.hobby) + 1];
    strcpy(hobby, c.hobby);
    weight = c.weight;
    return *this;
}
void Cow::showcow() const
{
    cout << "Name: " << name << " Hobby: " << hobby << endl;
    cout << "Weight: " << weight << endl;
}

上面的实现文件如果你放进vscode测试,一堆警告会绿得你发慌,但请相信我,能用。

#include <iostream>
#include "cow.h"
int main()
{
    Cow c1;
    Cow c2("miemie", "walking", 100);
    Cow c;
    c1.showcow();
    c2.showcow();
    c.showcow();
    c = c1;
    c.showcow();
    Cow s(c2);
    s.showcow();
    system("pause");
    return 0;
}

在这里插入图片描述

  1. 对书本中的实例string升级改进以实现以下功能:
    a.对+运算符重载,实现字符串合并;
    b.提供stringlow()成员函数,将字符串的字母转小写;
    c.提供string()成员函数使之字母转为大写;
    d.提供一个接受char参数的成员函数,返回字符在字符串中出现的次数。
    最后使用题目所示程序来测试工作。
#include <iostream>
using std::istream;
using std::ostream;
class String
{
private:
    char *str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;

public:
    //constructors and other methods
    String();
    String(const char *s);
    String(const String &s);
    ~String();
    int length() const { return len; }
    //overloaded operator function
    String &operator=(const String &s);
    String &operator=(const char *c);
    char &operator[](int i);
    const char &operator[](int i) const;
    //overloading friend functions
    friend bool operator<(const String &st, const String &st2);
    friend bool operator>(const String &st, const String &st2);
    friend bool operator==(const String &st, const String &st2);
    friend ostream &operator<<(ostream &os, const String &s);
    friend istream &operator>>(istream &is, String &s);
    //static function
    static int howmany();
    //functions added later
    String operator+(const String &s) const;
    String operator+(const char *c) const;
    friend String operator+(const char *c, const String &s);
    String Stringlow();
    String Stringup();
    int count(const char c) const;
};

函数方法实现源文件

(可能巴拉巴拉对你没什么实在好处,直接跳到后面方法实现那里看吧)
在这里就开始出现问题了,原因嘛,是我在构造函数和=重载函数还有复制构造函数中运用strcpy对成员进行赋值初始化,但由于新的标准不承认这种操作,以安全为由给我报错了。就是其实理论上是可行的,但标准更改,为了更安全就给限制了这种行为。

'strcpy' is deprecated: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. [Deprecations]Clang
并推荐了strcpy_s函数进行替换,查找资料cppreference.com得出:
char* strcpy( char* dest, const char* src );
复制src指向字符串到dest指向字符数组(包括空终止符),如果dest指向数组不够大或者字符串重叠都将报错未定义行为(undefined)。

strcpy_s( char *strDestination, size_t numberOfElements,
const char *strSource );
strcpy_s( char (&strDestination)[size], const char *strSource );
上面是三个参数和两个参数的版本,我参考了书本中的例子,所以很多构造函数都是在初始化时才new分配空间内存,但如果使用两个参数的版本,不能保证缓冲区大小,因而报错,但我在使用三个参数的版本却显示在这个区域无定义的情况,我就改成了下面这个函数(因为现在才认识这个函数,了解不足)继续查资料,发现c++并没有strcpy_s这个函数,这是vc独有的。

但是vs也各种问题,最后一个不算正面解决的办法
我在方法实现文件头加上了这句,然后解决掉对于静态成员num_strings的类外声明,整个问题就解决了,感谢看完我的挣扎之路。

#define _CRT_SECURE_NO_WARNINGS

方法实现文件

#define _CRT_SECURE_NO_WARNINGS
#include "String.h"
#include <string>
#include <cstring>
#include <cctype>
using std::strlen;
int String::num_strings;
//constructors and other methods
String::String()
{
    len = 0;
    str = new char[1];
    str[0] = '\0';
    num_strings++;
}
String::String(const char *s)
{
    len = strlen(s);
    str = new char[len + 1];
    strcpy(str, s);
    num_strings++;
}
String::String(const String &s)
{
    len = s.len;
    str = new char[len + 1];
    strcpy(str, s.str);
    num_strings++;
}
String::~String()
{
    delete[] str;
    num_strings--;
}
//overloaded operator function
String &String::operator=(const String &s)
{
    if (this == &s)
        return *this;
    delete[] str;
    len = s.len;
    str = new char[len + 1];
    strcpy(str, s.str);
    return *this;
}
String &String::operator=(const char *c)
{
    delete[] str;
    len = strlen(c);
    str = new char[len + 1];
    strcpy(str, c);
    return *this;
}
char &String::operator[](int i)
{
    return str[i];
}
const char &String::operator[](int i) const
{
    return str[i];
}
//overloading friend functions
bool operator<(const String &st, const String &st2)
{
    return (strcmp(st.str, st2.str) < 0);
}
bool operator>(const String &st, const String &st2)
{
    return st2 < st;
}
bool operator==(const String &st, const String &st2)
{
    return (strcmp(st.str, st2.str) == 0);
}
ostream &operator<<(ostream &os, const String &s)
{
    os << s.str;
    return os;
}
istream &operator>>(istream &is, String &s)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        s = temp;
    while (is && is.get() != '\n')
        continue;
    return is;
}
//static function
int String::howmany()
{
    return num_strings;
}
//functions added later
String String::operator+(const String &s) const
{
    String temp;
    temp.len = len + s.len;
    temp.str = new char[temp.len + 1];
    strcpy(temp.str, str);
    strcpy(temp.str + len, s.str);
    return temp;
}
String String::operator+(const char *c) const
{
    String temp;
    temp.len = len + strlen(c);
    temp.str = new char[temp.len + 1];
    strcpy(temp.str, str);
    strcpy(temp.str + len, c);
    return temp;
}
String operator+(const char *c, const String &s)
{
    return String(c) + s;
}
String String::Stringlow()
{
    for (int i = 0; i < length(); i++)
        str[i] = tolower(str[i]);
    return *this;
}
String String::Stringup()
{
    for (int j = 0; j < length(); j++)
        str[j] = toupper(str[j]);
    return *this;
}
int String::count(const char c) const
{
    int frequency = 0;
    for (int k = 0; k < length(); k++)
    {
        if (str[k] == c)
            frequency++;
    }
    return frequency;
}

测试程序用的是例子的

#include <iostream>
#include "String.h"
using std::cin;
using std::cout;
using std::endl;
int main()
{
    String s1(" and I am a C++ student.");
    String s2 = "Please enter your name: ";
    String s3;
    cout << s2;
    cin >> s3;
    s2 = "My name is " + s3;
    cout << s2 << "." << endl;
    s2 = s2 + s1;
    s2.Stringup();
    cout << "The string\n"
         << s2 << "\ncontains " << s2.count('A')
         << " 'A' characters in it." << endl;
    s1 = "red";
    String rgb[3] = {String(s1), String("green"), String("blue")};
    cout << "Enter the name of a primary color for mixing light: ";
    String ans;
    bool success = false;
    while (cin >> ans)
    {
        ans.Stringlow();
        for (int i = 0; i < 3; i++)
        {
            if (ans == rgb[i])
            {
                cout << "That's right!" << endl;
                success = true;
                break;
            }
        }
        if (success)
            break;
        else
            cout << "Try again!" << endl;
    }
    cout << "Bye." << endl;
    system("pause");
    return 0;
}

在这里插入图片描述

  1. 重写程序清单中的stock类,使用动态分配的内存,而非string对象来存储股票名称,另外重载<<来替代show函数,再使用10.9的测试程序。

声明头文件

#include <iostream>
using std::ostream;
class stock
{
private:
    char *company;
    int shares;
    double share_val;
    double total_val;
    void set_tot() { total_val = shares * share_val; }

public:
    stock();
    stock(const char *c, long n = 0, double pr = 0.0);
    ~stock();
    void buy(long num, double price);
    void shell(long num, double price);
    void update(double price);
    friend ostream &operator<<(ostream &os, const stock &s);
    const stock &topval(const stock &s) const;
};

方法实现

#define _CRT_SECURE_NO_WARNINGS
#include "stock.h"
#include <cstring>
using std::cout;
using std::endl;
stock::stock()
{
    company = new char[1];
    company[0] = '\0';
    shares = 0;
    share_val = 0.0;
    set_tot();
}
stock::stock(const char *c, long n, double pr)
{
    company = new char[strlen(c) + 1];
    strcpy(company, c);
    if (n < 0)
    {
        cout << "Negative numbers of the shares;" << company << " shares set to 0.";
        shares = 0;
    }
    else
        shares = n;
    share_val = pr;
    set_tot();
}
stock::~stock()
{
    delete[] company;
}
void stock::buy(long num, double price)
{
    if (num < 0)
        cout << "Negative numbers of the shares purchased.Aborting" << endl;
    else
    {
        shares += num;
        share_val = price;
        set_tot();
    }
}
void stock::shell(long num, double price)
{
    if (num > shares)
        cout << "Negative numbers of shares sold.Aborting.";
    else
    {
        shares -= num;
        share_val = price;
        set_tot();
    }
}
void stock::update(double price)
{
    share_val = price;
    set_tot();
}
ostream &operator<<(ostream &os, const stock &s)
{
    os << "Company:" << s.company << " Shares:" << s.shares << endl;
    os << "Share_val:$" << s.share_val << " total_val:$" << s.total_val << endl;
    return os;
}
const stock &stock::topval(const stock &s) const
{
    if (s.total_val > total_val)
        return s;
    else
        return *this;
}

测试程序

#include <iostream>
#include "stock.h"
const int STKs = 4;
int main()
{
    stock stocks[STKs] = {
        stock("NanoSmart", 12, 20.0),
        stock("Boffo objects", 200, 2.0),
        stock("Monolithic obelisks", 130, 3.25),
        stock("Fleep enterprises", 60, 6.5)};
    std::cout << "Stock holidings:" << std::endl;
    for (int st = 0; st < STKs; st++)
        std::cout << stocks[st];
    const stock *top = &stocks[0];
    for (int i = 1; i < STKs; i++)
        top = &top->topval(stocks[i]);
    std::cout << "\nMost valuable holdings :\n";
    std::cout << *top << std::endl;
    system("pause");
    return 0;
}

在这里插入图片描述

  1. 根据下面stack类定义编写方法实现和测试程序

stack类声明

typedef unsigned long Item;
class Stack
{
private:
    enum
    {
        MAX = 10
    };
    Item *pitems;
    int size;
    int top;

public:
    Stack(int n = MAX);
    Stack(const Stack &s);
    ~Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item &item);
    bool pop(Item &item);
    Stack &operator=(const Stack &s);
};

方法实现

#include <iostream>
#include "Stack.h"
Stack::Stack(int n)
{
    top = 0;
    pitems = new Item[n];
    size = n;
}
Stack::Stack(const Stack &s)
{
    pitems = new Item[s.size];
    size = s.size;
    top = s.top;
    for (int i = 0; i < top; i++)
        pitems[i] = s.pitems[i];
}
Stack::~Stack()
{
    delete[] pitems;
    pitems = nullptr;
}
bool Stack::isempty() const
{
    return top == 0;
}
bool Stack::isfull() const
{
    return top == size;
}
bool Stack::push(const Item &item)
{
    if (top < size)
    {
        pitems[top++] = item;
        return true;
    }
    else
        return false;
}
bool Stack::pop(Item &item)
{
    if (top > 0)
    {
        item = pitems[--top];
        return true;
    }
    else
        return false;
}
Stack &Stack::operator=(const Stack &s)
{
    if (this == &s)
        return *this;
    else
    {
        pitems = new Item[s.size];
        size = s.size;
        top = s.top;
        for (int i = 0; i < top; i++)
            pitems[i] = s.pitems[i];
        return *this;
    }
}

测试程序

#include <iostream>
#include <ctime>
#include <cstdlib>
#include "Stack.h"
using std::cout;
using std::endl;
int main()
{
    Stack st1(10);
    srand(time(0));
    for (size_t i = 0; i < 10; i++)
    {
        if (!st1.push(rand() % 100))
            cout << "Push error!" << endl;
    }
    if (!st1.push(0))
        cout << "Push 0 error!" << endl;
    Stack st2(st1);
    Stack st3 = st1;
    // 故意导致pop error
    for (size_t i = 0; i < 11; i++)
    {
        Item item;
        cout << "#" << i + 1 << ": " << endl;
        if (!st1.pop(item))
            cout << "st1 pop error!" << endl;
        else
            cout << "st1: " << item << endl;

        if (!st2.pop(item))
            cout << "st2 pop error!" << endl;
        else
            cout << "st2: " << item << endl;

        if (!st3.pop(item))
            cout << "st3 pop error!" << endl;
        else
            cout << "st3: " << item << endl;
        cout << endl;
    }
    system("pause");
    return 0;
}

结果图片太长,就不放粗来了。
5. 对书中队列的测试程序重写,测出排队时间不超过一分钟,则每小时到达的客户数是多少(实验时间不短于100小时)

队列声明头文件

class customer
{
private:
    long arrive;
    int processtime;

public:
    customer() { arrive = processtime = 0; }
    void set(long w);
    long when() const { return arrive; }
    int ptime() const { return processtime; }
};
typedef customer Item;
class Queue
{
private:
    struct node
    {
        Item item;
        struct node *next;
    };
    enum
    {
        Q_SIZE = 10
    };
    node *front;
    node *rear;
    int items;
    const int qsize;
    Queue(const Queue &q) : qsize(0) {}
    Queue &operator=(const Queue &q) { return *this; }

public:
    Queue(int qs = Q_SIZE);
    ~Queue();
    bool isempty() const;
    bool isfull() const;
    int queuecount() const;
    bool enqueue(const Item &item);
    bool dequeue(Item &item);
};

方法实现

#include <iostream>
#include <cstdlib>
#include "queue.h"
Queue::Queue(int qs) : qsize(qs)
{
    front = rear = NULL;
    items = 0;
}
Queue::~Queue()
{
    node *temp;
    while (front != NULL)
    {
        temp = front;
        front = front->next;
        delete temp;
    }
}
bool Queue::isempty() const
{
    return items == 0;
}
bool Queue::isfull() const
{
    return items == qsize;
}
int Queue::queuecount() const
{
    return items;
}
bool Queue::enqueue(const Item &item)
{
    if (isfull())
        return false;
    node *add = new node;
    add->item = item;
    add->next = NULL;
    items++;
    if (front == NULL)
        front = add;
    else
        rear->next = add;
    rear = add;
    return true;
}
bool Queue::dequeue(Item &item)
{
    if (front == NULL)
        return false;
    item = front->item;
    items--;
    node *temp = front;
    front = front->next;
    delete temp;
    if (items == 0)
        rear = NULL;
    return true;
}
//customer method
void customer::set(long w)
{
    processtime = std::rand() % 3 + 1;
    arrive = w;
}

测试程序

#include <iostream>
#include <ctime>
#include <cstdlib>
#include "queue.h"
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
using std::srand;
using std::time;
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main()
{
    srand(time(0));
    cout << "Case study:Bank of Heather Automatic Teller" << endl;
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;
    Queue line(qs);

    int hours = 100;
    long cyclelimit = MIN_PER_HR * hours;
    double perhour = 15;
    double min_per_hr;

    Item temp;
    double average_waiting_time = 0.0;

    do
    {
        min_per_hr = MIN_PER_HR / perhour;
        long served = 0;
        long line_wait = 0;
        long turnaways = 0;
        long customers = 0;
        long sum_line = 0;
        long wait_time = 0;
        while (!line.isempty())
        {
            line.dequeue(temp);
        }
        //running the simulation
        for (int cycle = 0; cycle < cyclelimit; cycle++)
        {
            if (newcustomer(min_per_hr))
            {
                if (line.isfull())
                    turnaways++;
                else
                {
                    customers++;
                    temp.set(cycle);
                    line.enqueue(temp);
                }
            }
            if (wait_time <= 0 && !line.isempty())
            {
                line.dequeue(temp);
                wait_time = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }
            if (wait_time > 0)
                wait_time--;
            sum_line += line.queuecount();
        }
        average_waiting_time = line_wait / served;
        //reporting
        if (customers > 0)
        {
            cout << "customers accepted: " << customers << endl;
            cout << "customers served: " << served << endl;
            cout << "turnaways: " << turnaways << endl;
            cout << "average queue size: ";
            cout.precision(2);
            cout.setf(ios_base::fixed, ios_base::floatfield);
            cout << (double)sum_line / cyclelimit << endl;
            cout << "average wait time: " << (double)line_wait / served << " minutes" << endl;
            cout << endl;
        }
        else
            cout << "No customers!" << endl;
    } while ((perhour++) && (average_waiting_time < 0.9) || (average_waiting_time > 1.1));
    cout.precision(0);
    cout << "The average of waiting time will be one minutes when the perhour is: " << perhour << endl;
    system("pause");
    return 0;
}
bool newcustomer(double x) { return (rand() * x / RAND_MAX < 1); }

在原有程序的条件下添加一个外部循环进行加一测试,得出结果。
在这里插入图片描述

  1. 在原有基础上新开一台ATM,也就是说原来的测试程序包含两个队列,并且在第一台人数少于第二台的时候,客户可排在第一队,否则排在第二队。同样平均等候时间为一分钟,程序显示每小时到达的客户数量。
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "queue.h"
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
using std::srand;
using std::time;
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main()
{
    srand(time(0));
    cout << "Case study:Bank of Heather Automatic Teller" << endl;
    cout << "Enter maximum size of queue: ";
    int qs;
    cin >> qs;
    Queue line1(qs);
    Queue line2(qs);

    int hours = 100;
    long cyclelimit = MIN_PER_HR * hours;
    double perhour = 15;
    double min_per_hr;

    Item temp;
    double average_waiting_time = 0.0;

    do
    {
        min_per_hr = MIN_PER_HR / perhour;
        long served = 0;
        long line_wait = 0;
        long turnaways = 0;
        long customers = 0;
        long sum_line = 0;
        long wait_time1 = 0;
        long wait_time2=0;
        long line_size1=0;
        long line_size2=0;
        while (!line1.isempty())
        {
            line1.dequeue(temp);
        }while (!line2.isempty())
        {
            line2.dequeue(temp);
        }
        //running the simulation
        for (int cycle = 0; cycle < cyclelimit; cycle++)
        {
            if (newcustomer(min_per_hr))
            {
                if (line1.isfull()&&line2.isfull())
                    turnaways++;
                    else if(line_size1>line_size2){
                        customers++;
                    temp.set(cycle);
                    line1.enqueue(temp);
                    line_size1++;
                    }
                else
                {
                    customers++;
                    temp.set(cycle);
                    line2.enqueue(temp);
                    line_size2++;
                }
            }
            if (wait_time1 <= 0 && !line1.isempty())
            {
                line1.dequeue(temp);
                wait_time1 = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }if (wait_time2 <= 0 && !line2.isempty())
            {
                line2.dequeue(temp);
                wait_time2 = temp.ptime();
                line_wait += cycle - temp.when();
                served++;
            }
            if (wait_time1 > 0)
                wait_time1--;
            if (wait_time2 > 0)
                wait_time2--;
            sum_line += line1.queuecount();
            sum_line+=line2.queuecount();
        }
        average_waiting_time = line_wait / served;
        //reporting
        if (customers > 0)
        {
            cout << "customers accepted: " << customers << endl;
            cout << "customers served: " << served << endl;
            cout << "turnaways: " << turnaways << endl;
            cout << "average queue size: ";
            cout.precision(2);
            cout.setf(ios_base::fixed, ios_base::floatfield);
            cout << (double)sum_line / cyclelimit << endl;
            cout << "average wait time: " << (double)line_wait / served << " minutes" << endl;
            cout << endl;
        }
        else
            cout << "No customers!" << endl;
    } while ((perhour++) && (average_waiting_time < 0.9) || (average_waiting_time > 1.1));
    cout.precision(0);
    cout << "The average of waiting time will be one minutes when the perhour is: " << perhour << endl;
    system("pause");
    return 0;
}
bool newcustomer(double x) { return (rand() * x / RAND_MAX < 1); }

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值