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

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