C++Primer Plus习题记录-Chapter12

12-1

//hf
#pragma once
#ifndef COW_H_
#define 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 // !COW_H_
//rf
#include "pch.h"
#include <iostream>
#include <cstring>
#include "cow.h"
using namespace std;
Cow::Cow() {
    name[0] = '\0';
    hobby = new char[1];
    hobby[0] = '\0';
    weight = 0;
}
Cow::Cow(const char* nm, const char* ho, double wt) {
    int len = strlen(nm);
    strcpy_s(name, len+1, nm);
    int len1 = strlen(ho);
    hobby = new char[len1+1];
    strcpy_s(hobby, len1+1, ho);
    weight = wt;
}
Cow::Cow(const Cow& c) {
    int len = strlen(c.hobby);
    int len1 = strlen(c.name);
    hobby = new char[len + 1];
    strcpy_s(hobby, len + 1, c.hobby);
    strcpy_s(name, len1 + 1, c.name);
    weight = c.weight;
}
Cow::~Cow() {
    delete[] hobby;
}
Cow& Cow::operator=(const Cow& c) {
    if (this == &c)
        return *this;
    delete[] hobby;
    int len = strlen(c.hobby);
    int len1 = strlen(c.name);
    hobby = new char[len + 1];
    strcpy_s(hobby, len + 1, c.hobby);
    strcpy_s(name, len1 + 1, c.name);
    weight = c.weight;
    return *this;
}
void Cow::ShowCow() const {
    cout << "name: " << name << endl;
    cout << "hobby: " << hobby << endl;
    cout << "weight: " << weight << endl;
}
//mf
#include "pch.h" #include "cow.h" int main(void) { Cow cows("w", "eat", 150); cows.ShowCow(); return 0; }

12-2

#pragma once
#ifndef STRING1_H_
#define STRING1_H_
#include <iostream>
using namespace std;
class String1 {
private:
    char* str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
public:
    String1(const char* s);
    String1();
    String1(const String1& s);
    ~String1();
    int length() const { return len; }
    void stringlow();
    void stringup();
    int has(char c);
    friend String1 operator+(const String1& st1, const String1& st2);
    String1 & operator=(const String1 & st);
    String1 & operator=(const char * s);
    char & operator[](int i);
    const char & operator[](int i) const;


    //友元运算符重载
    friend bool operator<(const String1 &st1, const String1 &st2);
    friend bool operator>(const String1 &st1, const String1 &st2);
    friend bool operator==(const String1 &st1, const String1 &st2);
    friend ostream & operator<<(ostream & os, const String1 &st);
    friend istream & operator>>(istream & is, String1 &st);

    static int HowMany();
};
#endif // !STRING1_H_


#include <cstring>
#include <cctype> 
#include "string2.h"
using std::cout;
using std::cin;

int String::num_strings = 0;//初始化为0,并且指出了类型
//初始化应该在方法文件中,不在类声明文件 

int String::HowMany()//静态方法 
{
    return num_strings; 
}

String::String(const char * s)
{
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);
    num_strings++;
}

String::String()
{
    len = 4;
    str = new char[1];
    str[0] = '\0';
    num_strings++;
}

String::String(const String & st)
{
    num_strings++;
    len = st.len;
    str = new char [len + 1];
    std::strcpy(str, st.str);
}

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

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

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

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

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

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

bool operator>(const String &st1, const String &st2)
{
    return st2 < st1;
}

bool operator==(const String &st1, const String &st2)
{
    return (std::strcmp(st1.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;
}

//新增函数的实现 
void String::stringlow()
{
    for (int i = 0; i < len;i++)
    {
        if(isupper((str[i])))
            str[i]= tolower(str[i]);
    }   
}

void String::stringup()
{
    for (int i = 0; i < len;i++)
    {
        if(islower((str[i])))
            str[i]= toupper(str[i]);
    }   
}

int String::has(char c)
{
    int count = 0;
    for (int i = 0; i < len;i++)
    {
        if( str[i]== c)
            count++;
    }
    return count;   
}
String operator+(const String &st1, const String &st2)
{
    String s;
    s.len = st1.len + st2.len;
    s.str = new char[s.len + 1];
    strcpy(s.str, st1.str);
    strcat(s.str, st2.str);
    return s;
}
#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.has('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;
}

 12-3

#pragma once
#ifndef STOCK_H_
#define STOCK_H_
#include <string>
using namespace std;
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* c0, long n = 0, double pr = 0.0);
    ~Stock();
    void buy(long num, double price);
    void sell(long num, double price);
    void update(double price);
    const Stock& topval(const Stock& s) const;
    
    friend std::ostream& operator<<(std::ostream& os, const Stock& st);
};
#endif // !STOCK_H_
#include "pch.h"
#include <iostream>
#include <cstring>
#include "stock.h"

Stock::Stock() {
    company = new char[1];
    company = '\0';
    shares = 0;
    share_val = 0.0;
    total_val = 0.0;
}
Stock::Stock(const char* c0, long n, double pr) {
    int len = 0;
    len = strlen(c0);
    company = new char[len + 1];
    strcpy_s(company,len + 1, c0);
    if (n < 0) {
        cout << "Number of shares can't be negative;" << company << " shares set to 0.\n";
        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 << "Number of shares purchased can't be negative. "<< "Transaction is aborted.\n";
    else {
        shares += num;
        share_val = price;
        set_tot();
    }
}
void Stock::sell(long num, double price) {
    if (num < 0)
    {
        cout << "Number of shares purchased can't be negative. "
            << "Transaction is aborted.\n";
    }
    else if (num > shares)
    {
        cout << "You can't sell more than you have! "
            << "Transaction is aborted.\n";
    }
    else
    {
        shares -= num;
        share_val = price;
        set_tot();
    }
}
void Stock::update(double price)
{
    share_val = price;
    set_tot();
}

const Stock & Stock::topval(const Stock & s) const
{
    if (s.total_val > total_val)
        return s;
    else
        return *this;
}

ostream & operator<<(ostream & os, const Stock & st)
{
    //set format to #.###
    ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield);
    streamsize prec = os.precision(3);

    os << "Company: " << st.company << "  Shares: " << st.shares << '\n';
    os << "  Share Price: $" << st.share_val;
    //set format to #.##
    os.precision(2);
    os << "  Total Worth: $" << st.total_val << '\n';

    //格式复原
    os.setf(orig, ios_base::floatfield);
    os.precision(prec);
    return os;
}

#include "pch.h"
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "stock.h"
const int STKS = 4;
int main(void) {
    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)
    };

    cout << "Stock holding:\n";
    int i;
    for (i = 0; i < STKS; i++)
        cout << stocks[i];

    const Stock * top = &stocks[0];
    for (i = 1; i < STKS; i++)
        top = &top->topval(stocks[i]);
    cout << "\nMost valuable holding:\n";
    cout << *top;
    return 0;
}
View Code

12-4

#pragma once
#ifndef STACK_H_
#define STACK_H_
typedef unsigned long Item;
class Stack {
private:
    enum { MAX = 10 };
    Item* pt;
    int size;
    int top;
public:
    Stack(int n = MAX);
    Stack(const Stack& st);
    ~Stack();
    bool isempty() const;
    bool isfull() const;
    bool push(const Item& item);
    bool pop(Item& item);
    Stack& operator=(const Stack& st);
};
#endif // !STACK_H_
#include "pch.h"
#include <cstring>
#include "stack.h"
Stack::Stack(int n) {
    size = n;
    pt = new Item[size];
    top = 0;
}
Stack::Stack(const Stack& st) {
    size = st.size;
    pt = new Item[size + 1];
    for (top = 0; top < size; top++)
        pt[top] = st.pt[top];
}
Stack::~Stack() {
    delete[] pt;
    size = 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) {
        pt[top++] = item;
        return true;
    }
    else
        return false;
}
bool Stack::pop(Item& item) {
    if (top > 0) {
        item = pt[--top];
        return true;
    }
    else
        return false;
}
Stack& Stack::operator=(const Stack& st) {
    if (this == &st)
        return *this;
    delete[] pt;
    size = st.size;
    pt = new Item[size + 1];
    for (top = 0; top < size; top++)
        pt[top] = st.pt[top];
    return *this;
}

12-6

#pragma once
#ifndef ATM_H_
#define ATM_H_
using namespace std;
class Customer {
private:
    long arrive;
    int processtime;
public:
    Customer() { arrive = 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;
        Node* next;
    };
    enum { Q_SIZE = 10 };
    Node* front;
    Node* rear;
    int items;
    const int qsize;
    //防止copy其他Queue的操作
    Queue(const Queue& q) :qsize(0) {}
    Queue& operator=(const Queue& q) { return *this; }
public:
    Queue(int qs = Q_SIZE);
    ~Queue();
    bool isempty() const { return items == 0; }
    bool isfull() const { return items == qsize; }
    int queuecount() const { return items; }
    bool enqueue(const Item& item);
    bool dequeue(Item& item);
    friend bool operator>(const Queue& item1, const Queue& item2);
};
#endif // !ATM_H_
#include "pch.h"
#include <cstdlib>
#include "atm.h"
Queue::Queue(int qs) :qsize(qs) {
    front = rear = nullptr;
    items = 0;
}
Queue::~Queue() {
    Node* temp;
    while (front!=nullptr)
    {
        temp = front;
        front = front->next;
        delete temp;
    }
}
bool Queue::enqueue(const Item& item) {
    if (isfull())
        return false;
    Node* add = new Node;
    add->item = item;
    add->next = nullptr;
    items++;
    if (front == nullptr)
        front = add;
    else
        rear->next = add;
    rear = add;
    return true;
}bool Queue::dequeue(Item& item) {
    if (front == nullptr)
        return false;
    item = front->item;
    items--;
    Node* temp = front;
    front = front->next;
    delete temp;
    if (items == 0)
        rear = nullptr;
    return true;
}
void Customer::set(long when) {
    processtime = rand() % 3 + 1;
    arrive = when;
}
bool operator>(const Queue& item1, const Queue& item2) {
    return item1.items > item2.items;
}
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "atm.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x);
int main(void) {
    srand(time(0));//随机初始化

    cout << "Case Study: Bank of Heather Automatic Teller\n";
    cout << "Enter maxmium size of queue: ";
    int qs;
    cin >> qs;
    Queue line1(qs);//设有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 hours: ";
    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 wait1_time = 0;
    int wait2_time = 0;
    long line1_wait = 0;
    long line2_wait = 0;

    for (int cycle = 0; cycle < cyclelimit; cycle++)
    {
        if (newcustomer(min_per_cust))
        {
            if (line1.isfull() && line2.isfull())
                turnaways++;
            else if (line2 > line1 || line1.isfull())
            {
                customers++;
                temp.set(cycle);
                line1.enqueue(temp);
            }
            else
            {
                customers++;
                temp.set(cycle);
                line2.enqueue(temp);
            }
        }
        if (wait1_time <= 0 && !line1.isempty())
        {
            line1.dequeue(temp);
            wait1_time = temp.ptime();
            line1_wait += cycle - temp.when();
            served++;
        }
        if (wait2_time <= 0 && !line2.isempty())
        {
            line2.dequeue(temp);
            wait2_time = temp.ptime();
            line2_wait += cycle - temp.when();
            served++;
        }
        if (wait1_time > 0)
            wait1_time--;
        sum_line += line1.queuecount();
        if (wait2_time > 0)
            wait2_time--;
        sum_line += line2.queuecount();
    }

    //报告结果 
    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)(line1_wait + line2_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);
}
View Code

猜你喜欢

转载自www.cnblogs.com/lightmonster/p/10452559.html