【C++ Primer Plus】编程练习答案——第12章

2021/9/26 14:10:52

本文主要是介绍【C++ Primer Plus】编程练习答案——第12章,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 1 // chapter12_1_cow.h
 2 
 3 
 4 #ifndef LEARN_CPP_CHAPTER12_1_COW_H
 5 #define LEARN_CPP_CHAPTER12_1_COW_H
 6 
 7 class Cow {
 8 private:
 9     char name_[20];
10     char * hobby_;
11     double weight_;
12 public:
13     Cow();
14     Cow(const char * name, const char * hobby, double weight);
15     Cow(const Cow & c);
16     ~Cow();
17     Cow & operator=(const Cow & c);
18     void showcow() const;
19 };
20 
21 
22 #endif //LEARN_CPP_CHAPTER12_1_COW_H
23 
24 
25 // chapter12_1_cow.cpp
26 
27 #include "chapter12_1_cow.h"
28 #include <cstring>
29 #include <iostream>
30 
31 Cow::Cow() {
32     name_[0] = '\0';
33     hobby_ = nullptr;
34     weight_ = 0;
35 }
36 
37 Cow::Cow(const char * name, const char * hobby, double weight) {
38     strcpy(name_, name);
39     hobby_ = new char[strlen(hobby)];
40     strcpy(hobby_, hobby);
41     weight_ = weight;
42 }
43 
44 Cow::Cow(const Cow &c) {
45     strcpy(name_, c.name_);
46     if (!hobby_) delete [] hobby_;
47     hobby_ = new char[strlen(c.hobby_)];
48     strcpy(hobby_, c.hobby_);
49     weight_ = c.weight_;
50 }
51 
52 Cow::~Cow() {
53     delete [] hobby_;
54 }
55 
56 Cow & Cow::operator=(const Cow & c) {
57     strcpy(name_, c.name_);
58     if (!hobby_) delete [] hobby_;
59     hobby_ = new char[strlen(c.hobby_)];
60     strcpy(hobby_, c.hobby_);
61     weight_ = c.weight_;
62     return *this;
63 }
64 
65 void Cow::showcow() const {
66     using namespace std;
67     cout << "name: " << name_ << endl
68         << "hobby: " << hobby_ << endl
69         << "weight: " << weight_ << endl;
70 }
71 
72 // run
73 
74 void ch12_1() {
75     Cow a("nma", "tennis", 70);
76     Cow b("nmb", "football", 65);
77     a.showcow();
78     b.showcow();
79     b = a;
80     b.showcow();
81     Cow c(a);
82     c.showcow();
83 }
// chapter12_2_string2.h


#ifndef LEARN_CPP_CHAPTER12_2_STRING2_H
#define LEARN_CPP_CHAPTER12_2_STRING2_H

#include <iostream>
using std::istream;
using std::ostream;

class string2 {
private:
    char * str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
public:
    string2();
    string2(const string2 & s);
    string2(const char * s);
    ~string2();
    int length() const {return len;}
    int charnum(char ch) const; // d
    string2 & stringlow(); // b
    string2 & stringup(); // c

    string2 & operator=(const string2 & s);
    string2 & operator=(const char * s);
    char & operator[](int i);
    const char & operator[](int i) const;

    friend bool operator<(const string2 & s1, const string2 & s2);
    friend bool operator>(const string2 & s1, const string2 & s2);
    friend bool operator==(const string2 & s1, const string2 & s2);
    friend ostream & operator<<(ostream & os, const string2 & s);
    friend istream & operator>>(istream & is, string2 & s);
    friend string2 & operator+(string2 & s1, const string2 & s2); // a

    static int howmany();
};


#endif //LEARN_CPP_CHAPTER12_2_STRING2_H


// chapter12_2_string2.cpp

#include "chapter12_2_string2.h"

#include <cstring>
#include <cctype>

int string2::num_strings = 0;

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

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

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

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

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

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

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

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

int string2::howmany() {
    return num_strings;
}

bool operator<(const string2 & s1, const string2 & s2) {
    return (std::strcmp(s1.str, s2.str) < 0);
}

bool operator>(const string2 & s1, const string2 & s2) {
    return s2 < s1;
}

bool operator==(const string2 & s1, const string2 & s2) {
    return (std::strcmp(s1.str, s2.str) == 0);
}

ostream & operator<<(ostream & os, const string2 & s) {
    os << s.str;
    return os;
}

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

int string2::charnum(char ch) const {
    int i = 0, num = 0;
    while (str[i] != '\0') {
        if (str[i] == ch)
            ++ num;
        ++ i;
    }
    return num;
}

string2 &string2::stringlow() {
    int i = 0;
    while (str[i] != '\0') {
        if (std::isalpha(str[i]))
            str[i] = std::toupper(str[i]);
        ++ i;
    }
    return *this;
}

string2 &string2::stringup() {
    int i = 0;
    while (str[i] != '\0') {
        if (std::isalpha(str[i]))
            str[i] = std::tolower(str[i]);
        ++ i;
    }
    return *this;
}

string2 & operator+(string2 & s1, const string2 & s2) {
    char * temp = new char[s1.len];
    std::strcpy(temp, s1.str);
    delete [] s1.str;
    s1.str = new char[s1.len + s2.len + 1];
    s1.len += s2.len;
    std::strcpy(s1.str, temp);
    std::strcat(s1.str, s2.str);
    return s1;
}

// run

void ch12_2() {
    using namespace std;
    string2 s1(" and I am a C++ student.");
    string2 s2 = "Please enter your name: ";
    string2 s3;
    cout << s2;
    cin >> s3;
    string2 t("My name is ");
    s2 = t + s3;
    cout << s2 << ".\n";
    s2 = s2 + s1;
    s2.stringup();
    cout << "The string\n" << s2 << "\ncontains " << s2.charnum('A')
        << " 'A' characters in it.\n";
    s1 = "red";
    string2 rgb[3] = {string2(s1), string2("green"), string2("blue")};
    cout << "Enter the name of a primary color for mixing light: ";
    string2 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";
}
  1 // chapter12_3_stock.h
  2 
  3 
  4 void ch12_2() {
  5     using namespace std;
  6     string2 s1(" and I am a C++ student.");
  7     string2 s2 = "Please enter your name: ";
  8     string2 s3;
  9     cout << s2;
 10     cin >> s3;
 11     string2 t("My name is ");
 12     s2 = t + s3;
 13     cout << s2 << ".\n";
 14     s2 = s2 + s1;
 15     s2.stringup();
 16     cout << "The string\n" << s2 << "\ncontains " << s2.charnum('A')
 17         << " 'A' characters in it.\n";
 18     s1 = "red";
 19     string2 rgb[3] = {string2(s1), string2("green"), string2("blue")};
 20     cout << "Enter the name of a primary color for mixing light: ";
 21     string2 ans;
 22     bool success = false;
 23     while (cin >> ans) {
 24         ans.stringlow();
 25         for (int i = 0; i < 3; ++ i) {
 26             if (ans == rgb[i]) {
 27                 cout << "That's right!\n";
 28                 success = true;
 29                 break;
 30             }
 31         }
 32         if (success)
 33             break;
 34         else
 35             cout << "Try again!\n";
 36     }
 37     cout << "Bye\n";
 38 }
 39 
 40 
 41 // chapter12_3_stock.cpp
 42 
 43 #include "chapter12_3_stock.h"
 44 
 45 #include <iostream>
 46 #include <cstring>
 47 
 48 stock::stock() {
 49     company = new char[8];
 50     len = 7;
 51     strcpy(company, "no name");
 52     shares = 0;
 53     share_val = 0.0;
 54     total_val = 0.0;
 55 }
 56 
 57 stock::stock(const char * co, long n, double pr) {
 58     len = strlen(co);
 59     company = new char[len + 1];
 60     strcpy(company, co);
 61     if (n < 0) {
 62         std::cout << "Number of shares can't be negative; "
 63             << company << " shares set to 0.\n";
 64         shares = 0;
 65     }
 66     else
 67         shares = n;
 68     share_val = pr;
 69     set_tot();
 70 }
 71 
 72 stock::~stock() {
 73     delete [] company;
 74 }
 75 
 76 void stock::buy(long num, double price) {
 77     if (num < 0) {
 78         std::cout << "Number of shares purchased can't be nagetive. "
 79             << "Transaction is aborted.\n";
 80     }
 81     else {
 82         shares += num;
 83         share_val = price;
 84         set_tot();
 85     }
 86 }
 87 
 88 void stock::sell(long num, double price) {
 89     using std::cout;
 90     if (num < 0) {
 91         cout << "Number of shares sold can't be negative. "
 92             << "Transaction is aborted.\n";
 93     }
 94     else {
 95         shares -= num;
 96         share_val = price;
 97         set_tot();
 98     }
 99 }
100 
101 void stock::update(double price) {
102     share_val = price;
103     set_tot();
104 }
105 
106 void stock::show() const {
107     using std::cout;
108     using std::ios_base;
109     ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
110     std::streamsize  prec = cout.precision(3);
111     cout << "Company: " << company
112         << "  Shares: " << shares << '\n';
113     cout << "Shares Prices: $" << share_val << '\n';
114     cout.precision(2);
115     cout << "Total Worth: $" << total_val << '\n';
116     cout.setf(orig, ios_base::floatfield);
117     cout.precision(prec);
118 }
119 
120 const stock &stock::topval(const stock &s) const {
121     if (s.total_val > total_val)
122         return s;
123     return *this;
124 }
125 
126 std::ostream &operator<<(std::ostream & os, const stock & s) {
127     os << "Company: " << s.company
128     << "  Shares: " << s.shares << '\n';
129     os << "Shares Prices: $" << s.share_val << '\n';
130     os.precision(2);
131     os << "Total Worth: $" << s.total_val << '\n';
132 }
133 
134 
135 // run
136 
137 
138 
139 void ch12_3() {
140     using namespace std;
141     const int STKS = 4;
142     stock ss[STKS] = {
143             stock("NanoSmart", 12, 20.0),
144             stock("Boffo Objects", 200, 2.0),
145             stock("Monolithic Obelisks", 130, 3.25),
146             stock("Fleep Enterprises", 60, 6.5)
147     };
148     cout << "Stock holdings: \n";
149     int st;
150     for (st = 0; st < STKS; ++ st)
151         cout << ss[st];
152     const stock * top = &ss[0];
153     for (st = 1; st < STKS; ++ st)
154         top = &top -> topval(ss[st]);
155     cout << "\nMost valuable holding:\n";
156     cout << *top;
157 }
  1 // chapter12_4_stack.h
  2 
  3 
  4 #ifndef LEARN_CPP_CHAPTER12_4_STACK_H
  5 #define LEARN_CPP_CHAPTER12_4_STACK_H
  6 
  7 typedef unsigned long Item;
  8 
  9 class Stack {
 10 private:
 11     enum {MAX = 10};
 12     Item * pitems;
 13     int size;
 14     int top;
 15 public:
 16     Stack(int n = MAX);
 17     Stack(const Stack & st);
 18     ~Stack();
 19     bool isempty() const;
 20     bool isfull() const;
 21     bool push(const Item & item);
 22     bool pop(Item & item);
 23     void show() const;
 24     Stack & operator=(const Stack & st);
 25 };
 26 
 27 
 28 
 29 
 30 #endif //LEARN_CPP_CHAPTER12_4_STACK_H
 31 
 32 // chapter12_4_stack.cpp
 33 
 34 #include "chapter12_4_stack.h"
 35 #include <iostream>
 36 
 37 Stack::Stack(int n) {
 38     pitems = new Item[n];
 39     size = n;
 40     top = 0;
 41 }
 42 
 43 Stack::Stack(const Stack &st) {
 44     pitems = new Item[st.size];
 45     size = st.size;
 46     top = st.top;
 47     for (int i = 0; i < st.top; ++ i)
 48         pitems[i] = st.pitems[i];
 49 }
 50 
 51 Stack::~Stack() {
 52     delete [] pitems;
 53 }
 54 
 55 bool Stack::isempty() const {
 56     if (top == 0)
 57         return true;
 58     return false;
 59 }
 60 
 61 bool Stack::isfull() const {
 62     if (top == size)
 63         return true;
 64     return false;
 65 }
 66 
 67 bool Stack::push(const Item &item) {
 68     if (isfull())
 69         return false;
 70     pitems[top ++] = item;
 71     return true;
 72 }
 73 
 74 bool Stack::pop(Item &item) {
 75     if (isempty())
 76         return false;
 77     item = pitems[-- top];
 78     return true;
 79 }
 80 
 81 Stack &Stack::operator=(const Stack &st) {
 82     if (this == &st)
 83         return *this;
 84     if (pitems)
 85         delete [] pitems;
 86     pitems = new Item[st.size];
 87     size = st.size;
 88     top = st.top;
 89     for (int i = 0; i < st.top; ++ i)
 90         pitems[i] = st.pitems[i];
 91     return *this;
 92 }
 93 
 94 void Stack::show() const {
 95     using namespace std;
 96     cout << "Stack: ";
 97     for (int i = 0; i < top; ++ i)
 98         cout << pitems[i] << " ";
 99     cout << endl;
100 }
101 
102 // run
103 
104 void ch12_4() {
105     Stack s1(15);
106     s1.show();
107     s1.push(1234);s1.push(123);s1.push(12);
108     s1.show();
109     Item t = 0;
110     s1.pop(t);
111     s1.show();
112 
113     Stack s2(s1);
114     s2.show();
115     s2.push(12345);
116     s2.show();
117 
118     Stack s3 = s1;
119     s3.show();
120     s3.pop(t);
121     s3.show();
122 }
// ch12_5&5

// 待更新

 



这篇关于【C++ Primer Plus】编程练习答案——第12章的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程