C++ primer plus 课后练习题

第十二章:类和动态内存分配

        一、复习题

        1. a. 并没有初始化成员,会出现野指针。

            b. 应该使用strcpy()函数进行对str的初始化。(没有创建新的字符串)

            c. 虽然复制了字符串,但是没有分配对应的内存空间

        2. 第一,使用系统默认的析构函数时,类中成员所占的内存空间不会被释放,需要手动编写析构函数;第二,在进行复制构造时,系统不会新new出空间,可能导致内存的重复释放,需要手动编写对应的复制构造函数;第三,将一个对象赋给另一个对象也将导致两个指针指向相同的数据,需要重载赋值运算符。

        3. 将自动生成:默认构造函数,默认复制构造函数,默认重载=的函数,默认重载&的函数,默认析构函数

        4. 第一,对于使用new的成员指针,并未提供相应的含delete的析构函数,这可能会导致内存泄漏;第二,在对成员指针进行初始化时,应当使用strcpy()函数;第三,在重载<<运算符的方法中,忘记return对象的引用;(没有初始化成员数组长度,没有对共有接口声明public,nifty函数中的参数应为const,未将重载<<运算符的方法声明为友元)

        5. a. #1:默认构造函数;#2:含参构造函数;#3:含参构造函数;#4:默认构造函数;#5:复制构造函数;#6:含参构造函数;#7:默认赋值运算符函数;#8:复制构造函数和默认赋值运算符函数

            b. 类应定义一个复制数据(而不是地址)的赋值运算符

        二、编程练习

        1.

#ifndef C_PRIMER_CHAPTER12_COW_H
#define C_PRIMER_CHAPTER12_COW_H

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

#endif //C_PRIMER_CHAPTER12_COW_H

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

Cow::Cow()
{
    strcpy(name,"");
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0;
}

Cow::Cow(const char* nm, const char* ho, double wt)
{
    strcpy(name,nm);
    int len = strlen(ho);
    hobby = new char[len+1];
    strcpy(hobby,ho);
    weight = wt;
}

Cow::Cow(const Cow& c)
{
    strcpy(name,c.name);
    int len = strlen(c.hobby);
    hobby = new char[len+1];
    strcpy(hobby,c.hobby);
    weight = c.weight;
}

Cow::~Cow()
{
    delete[] hobby;
}

Cow& Cow::operator=(const Cow& c)
{
    strcpy(name,c.name);
    int len = strlen(c.hobby);
    hobby = new char[len+1];
    strcpy(hobby,c.hobby);
    weight = c.weight;
    return *this;
}

void Cow::showCow() const
{
    using std::cout;
    using std::endl;

    cout << "name: " << name << endl;
    cout << "hobby: " << hobby << endl;
    cout << "weight: " << weight << endl;

}
#include "Cow.h"

int main()
{
    Cow c1;
    Cow c2("David","Playing",50);

    Cow c3 = c2;
    Cow c4(c2);

    c1.showCow();
    c2.showCow();
    c3.showCow();
    c4.showCow();

    return 0;
}

        2.

#ifndef C_PRIMER_CHAPTER12_STRING2_H
#define C_PRIMER_CHAPTER12_STRING2_H

#include <iostream>

using std::ostream;
using std::istream;

class String {
private:
    char *str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
public:
    String();

    String(const char *s);

    String(const String &str);

    ~String();

    int length() const { return len; }

    void Stringlow();

    void Stringup();

    int appear_times(const char);

    String &operator=(const String &str);

    String &operator=(const char *s);

    String operator+(const char *st) const;

    String operator+(const String &st) const;

    char &operator[](int i);

    const char &operator[](int i) const;

    friend String operator+(const char *st, const String &st2);

    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 &st);

    friend istream &operator>>(istream &is, String &st);

    static int HowMany();
};

#endif //C_PRIMER_CHAPTER12_STRING2_H
#include "String2.h"
#include <cstring>

int String::num_strings = 0;

String::String() {
    len = 4;//
    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 &str) {
    len = str.len;
    this->str = new char[len + 1];
    strcpy(this->str, str.str);
    num_strings++;
}

String::~String() {
    delete[] str;
    num_strings--;
}

void String::Stringlow() {
    for (int i = 0; i < len; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') {
            str[i] += 32;
        }
    }
}

void String::Stringup() {
    for (int i = 0; i < len; i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            str[i] -= 32;
        }
    }
}

int String::appear_times(const char c) {
    int count = 0;
    for (int i = 0; i < len; i++) {
        if (str[i] == c) {
            count++;
        }
    }
    return count;
}

String &String::operator=(const String &st) {
    if (this == &st)  //
        return *this;//
    delete[] str;
    len = st.len;
    str = new char[len + 1];
    strcpy(str, st.str);
    return *this;
}

String &String::operator=(const char *s) {
    delete[] str;
    len = strlen(s);
    str = new char[len + 1];
    strcpy(str, s);
    return *this;
}

String String::operator+(const char *st) const {
    String temp;
    temp.len = len + strlen(st);
    temp.str = new char[temp.len + 1];
    char *newstr = strcat(str, st);
    strcpy(temp.str, newstr);
    return temp;
}

String String::operator+(const String &st) const {
    String temp;
    temp.len = len + st.len;
    temp.str = new char[temp.len + 1];
    char *newstr = strcat(str, st.str);
    strcpy(temp.str, newstr);
    return temp;
}

String operator+(const char *st, const String &st2) {
    String temp;
    temp.len = strlen(st) + st2.len;
    temp.str = new char[temp.len + 1];
    strcat(temp.str, st);
    strcat(temp.str, st2.str);
    return temp;
}

char &String::operator[](int i) {
    return str[i];
}

const char &String::operator[](int i) const {
    return str[i];
}

bool operator<(const String &st, const String &st2) {
    return strcmp(st.str, st2.str) < 0;
}

bool operator>(const String &st, const String &st2) {
    return strcmp(st.str, st2.str) > 0;
}

bool operator==(const String &st, const String &st2) {
    return strcmp(st.str, st2.str) == 0;
}

ostream &operator<<(ostream &os, const String &st) {
    os << st.str;
    return os;
}

istream &operator>>(istream &is, String &st) {
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is) {
        st = temp;
    }
    while (is && is.get() != '\n')
        continue;
    return is;
}

int String::HowMany() {
    return num_strings;
}
#include <iostream>

using namespace std;

#include "String2.h"

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 << ".\n";
    s2 = s2 + s1;
    s2.Stringup();
    cout << "The string\n" << s2 << "\ncontains " << s2.appear_times('A')
         << " 'A' characters in it.\n";
    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!\n";
                success = true;
                break;
            }
        }
        if (success)
            break;
        else
            cout << "Try again!\n";
    }
    cout << "Bye\n";

    return 0;
}

        3.

#ifndef C_PRIMER_CHAPTER12_STOCK20_H
#define C_PRIMER_CHAPTER12_STOCK20_H

class Stock
{
private:
    char* company;
    int shares;
    double share_val;
    double total_val;
    void set_tot() {total_val = share_val * shares;}
public:
    Stock();
    Stock(const char* nm, long n = 0, double pr = 0);
    ~Stock();
    void buy(long num, double price);
    void sell(long num, double price);
    void update(double price);
    void show() const;
    const Stock& topval(const Stock& s) const;
};

#endif //C_PRIMER_CHAPTER12_STOCK20_H
#include "Stock20.h"
#include <cstring>
#include <iostream>

Stock::Stock()
{
    company = new char[1];
    company[0] = '\0';
    shares = 0;
    share_val = 0.0;
    set_tot();
}

Stock::Stock(const char* nm, long n, double pr)
{
    company = new char[strlen(nm)+1];
    strcpy(company,nm);
    shares = n;
    share_val = pr;
    set_tot();
}

Stock::~Stock()
{
    delete company;
}

void Stock::buy(long num, double price)
{
    shares += num;
    share_val = price;
    set_tot();
}

void Stock::sell(long num, double price)
{
    shares -= num;
    share_val = price;
    set_tot();
}

void Stock::update(double price)
{
    share_val = price;
    set_tot();
}

void Stock::show() const
{
    using std::cout;
    using std::endl;
    cout << "Company: " << company << " "
         << "Shares: " << shares << " "
         << "Share Price: $" << share_val << " "
         << " Total Worth: " << total_val << endl;
}
const Stock& Stock::topval(const Stock& s) const
{
    if(s.total_val > total_val)
        return s;
    else
        return *this;
}
#include "Stock20.h"

int main()
{
    Stock s1;
    Stock s2("David",100,20);
    s1.show();
    s2.show();

    s2.buy(200,10);
    s2.show();

    s2.update(30);
    s2.show();

    s2.sell(250,30);
    s2.show();

    s2.topval(s1).show();

    return 0;
}

        4.

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

using namespace std;

int main()
{
    Stack s1(3);

    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);

    Stack s2 = s1;

    Item a;
    s2.pop(a);
    cout << a << endl;
    s2.pop(a);
    cout << a << endl;
    s2.pop(a);
    cout << a << endl;
    cout << s2.pop(a) << endl;
    cout << a << endl;


    return 0;
}

        5.

#ifndef C_PRIMER_CHAPTER12_QUEUE_H
#define C_PRIMER_CHAPTER12_QUEUE_H

class Customer
{
private:
    long arrive;
    int processtime;
public:
    Customer(){arrive = 0;processtime = 0;}

    void set(long when);
    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 queueconut() const;
    bool enqueue(const Item& item);
    bool dequeue(Item& item);
};

#endif //C_PRIMER_CHAPTER12_QUEUE_H

​​​​​​​

#include "Queue.h"
#include <cstdlib>

void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when;
}

Queue::Queue(int qs) : qsize(qs)
{
    front = nullptr;
    rear = nullptr;
    items = 0;
}

Queue::~Queue()
{
    Node* temp;
    while(front != nullptr)
    {
        temp = front->next;
        delete front;
        front = temp;
    }
}

bool Queue::isempty() const
{
    return items == 0;
}
bool Queue::isfull() const
{
    return qsize == items;
}
int Queue::queueconut() const
{
    return items;
}

bool Queue::enqueue(const Item& item)
{
    if(isfull())
        return false;
    Node* newNode = new Node;
    newNode->item = item;
    newNode->next = nullptr;
    if(front == nullptr)
        front = newNode;
    else
        rear->next = newNode;
    rear = newNode;
    items++;
    return true;
}

bool Queue::dequeue(Item& item)
{
    if(front == nullptr)
        return false;

    item = front->item;
    items--;

    Node* temp;
    temp = front->next;
    delete front;
    front = temp;

    if(items == 0)
        rear = nullptr;

    return true;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Queue.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
    std::srand(time(0));

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maxium size of queue: ";
    int qs;
    cin >> qs;
    Queue line(qs);

    cout << "Enter the number of simulation hours: ";
    int hours;
    cin >> hours;
    long cyclelimit = MIN_PER_HR * hours;

    cout << "Enter the average number of customers per hour: ";
    double perhour;
    cin >> perhour;
    double min_per_cust;
    min_per_cust = MIN_PER_HR / perhour;

    Item temp;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    int wait_time = 0;
    long line_wait = 0;

    for(int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if(newcustomer(min_per_cust))
        {
            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.queueconut();
    }

    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.\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";

    return 0;
}

bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1);
}
Enter maxium size of queue: 10
Enter the number of simulation hours: 100
Enter the average number of customers per hour: 18
customers accepted: 1820
customers served: 1820
turnaways: 0
average queue size: 0.29
average wait time: 0.97 minutes.

        6.

#ifndef C_PRIMER_CHAPTER12_QUEUE_H
#define C_PRIMER_CHAPTER12_QUEUE_H

class Customer
{
private:
    long arrive;
    int processtime;
public:
    Customer(){arrive = 0;processtime = 0;}

    void set(long when);
    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 queueconut() const;
    bool enqueue(const Item& item);
    bool dequeue(Item& item);
};

#endif //C_PRIMER_CHAPTER12_QUEUE_H
#include "Queue.h"
#include <cstdlib>

void Customer::set(long when)
{
    processtime = std::rand() % 3 + 1;
    arrive = when;
}

Queue::Queue(int qs) : qsize(qs)
{
    front = nullptr;
    rear = nullptr;
    items = 0;
}

Queue::~Queue()
{
    Node* temp;
    while(front != nullptr)
    {
        temp = front->next;
        delete front;
        front = temp;
    }
}

bool Queue::isempty() const
{
    return items == 0;
}
bool Queue::isfull() const
{
    return qsize == items;
}
int Queue::queueconut() const
{
    return items;
}

bool Queue::enqueue(const Item& item)
{
    if(isfull())
        return false;
    Node* newNode = new Node;
    newNode->item = item;
    newNode->next = nullptr;
    if(front == nullptr)
        front = newNode;
    else
        rear->next = newNode;
    rear = newNode;
    items++;
    return true;
}

bool Queue::dequeue(Item& item)
{
    if(front == nullptr)
        return false;

    item = front->item;
    items--;

    Node* temp;
    temp = front->next;
    delete front;
    front = temp;

    if(items == 0)
        rear = nullptr;

    return true;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Queue.h"
const int MIN_PER_HR = 60;

bool newcustomer(double x);

int main()
{
    using std::cin;
    using std::cout;
    using std::endl;
    using std::ios_base;
    std::srand(time(0));

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maxium size of the 1st queue: ";
    int qs;
    cin >> qs;
    Queue line(qs);

    cout << "Enter maxium size of the 2nd queue: ";
    cin >> qs;
    Queue line2(qs);

    cout << "Enter the number of simulation hours: ";
    int hours;
    cin >> hours;
    long cyclelimit = MIN_PER_HR * hours;

    cout << "Enter the average number of customers per hour: ";
    double perhour;
    cin >> perhour;
    double min_per_cust;
    min_per_cust = MIN_PER_HR / perhour;

    Item temp;
    long turnaways = 0;
    long customers = 0;
    long served = 0;
    long sum_line = 0;
    int wait_time = 0;
    long line_wait = 0;

    for(int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if(newcustomer(min_per_cust))
        {
            if (line.isfull())
                turnaways++;
            else {
                customers++;
                temp.set(cycle);
                line.queueconut() > line2.queueconut() ? line2.enqueue(temp) : line.enqueue(temp);
            }
        }
        if(wait_time <= 0 && (!line.isempty() || !line2.isempty()))
        {
            if(!line.isempty())
                line.dequeue(temp);
            else if(!line2.isempty())
                line2.dequeue(temp);
            wait_time = temp.ptime();
            line_wait += cycle - temp.when();
            served++;
        }
        if(wait_time > 0)
            wait_time--;
        sum_line += line.queueconut();
        sum_line += line2.queueconut();
    }

    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.\n";
    }
    else
        cout << "No customers!\n";
    cout << "Done!\n";

    return 0;
}

bool newcustomer(double x)
{
    return (std::rand() * x / RAND_MAX < 1);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值