【学习C++】C++ Primer Plus (第六版)第十二章编程练习1-6

来源:互联网 发布:70大中城市房价数据 编辑:程序博客网 时间:2024/05/20 09:07
1.
//cow.h#ifndef COW_H_#define COW_H_#include<iostream>using namespace std; class Cow{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
<pre name="code" class="cpp">//cow.cpp#include<iostream>#include "cow.h"using namespace std;Cow::Cow(){std::strcpy(name, "no name");hobby = new char[10];std::strcpy(hobby, "no hobby");weight = 0;std::cout << "construct " << name << endl;}Cow::Cow(const char * nm, const char * ho, double wt){std::strcpy(name, nm);int len = std::strlen(ho);hobby = new char[len+1];std::strcpy(hobby, ho);weight = wt;std::cout << "construct " << name << endl;}Cow::Cow(const Cow &c){std::strcpy(name, c.name);int len = std::strlen(c.hobby);hobby = new char[len + 1];std::strcpy(hobby, c.hobby);weight = c.weight;std::cout << "construct " << name << endl;}Cow::~Cow(){delete [] hobby;std::cout << "delete " << name << endl;}Cow & Cow::operator=(const Cow & c){        if(this==&str)             return *this;
        strcpy(name,c.name);        delete[] hobby;int len = std::strlen(c.hobby);hobby = new char[len + 1];std::strcpy(hobby, c.hobby);weight = c.weight;return *this;}void Cow::ShowCow() const{std::cout << "name : " << name << std::endl;std::cout << "hobby : " << hobby << std::endl;std::cout << "weight : " << weight << std::endl;}


//main.cpp#include <iostream>#include "cow.h"int main(){{Cow a;//调用Cow();Cow b("daniu", "chicao", 50);//调用Cow(const char * nm, const char * ho, double wt)a.ShowCow();//调用ShowCow() constb.ShowCow();Cow c = b;//调用Cow(const Cow &c)c.ShowCow();c = a;//调用operator=(const Cow & c)c.ShowCow();}cin.get();return 0;}
2.
//string2.h#ifndef STRING2_H_#define STRING2_H_#include<iostream>using namespace std; class String{private:char * str;int len;static const int CINLIM = 80;public:String(const char * s);String();String(const String &);~String();int length() const{ return len; }String & operator=(const String &);String & operator=(const char *);char & operator[](int i);const char & operator[](int i) const;void stringlow();void stringup();int has(const char);friend String operator+(const String &st1,const String &st2);friend bool operator==(const String &st1, const String &st2);friend ostream & operator<<(ostream & os, const String &st);friend istream & operator>>(istream & is, String &st);};#endif
//string2.cpp#include<iostream>#include<cstring>#include "string2.h"using namespace std;String::String(const char * s){len = strlen(s);str = new char[len + 1];strcpy(str, s);}String::String(){len = 0;str = new char[1];str[0] = '\0';}String::String(const String & st){len = st.len;str = new char[len + 1];strcpy(str, st.str);}String::~String(){delete [] str;}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;}char & String::operator[](int i){return str[i];}const char & String::operator[](int i) const{return str[i];}void String::stringlow(){for (int i = 0; i < len; i++){str[i] = tolower(str[i]);}}void String::stringup(){for (int i = 0; i < len; i++){str[i] = toupper(str[i]);}}int String::has(const char a){int count=0;for (int i = 0; i < len; i++){if (str[i] == a)count++;}return count;}String operator+(const String &st1, const String &st2){String a;a.len = st1.len + st2.len;delete [] a.str;a.str = new char[a.len + 1];a.str[0] = '\0';strcat(a.str, st1.str);strcat(a.str, st2.str);return a;}bool operator==(const String &st1, const String &st2){return (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;}
//main.cpp#include <iostream>#include "string2.h"using namespace std;int main(){String s1(" and I am a 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 is right!\n";success = true;break;}}if (success)break;elsecout << "Try again!\n";}cout << "Bye\n";cin.get();return 0;}
3.
//stock.h#ifndef STOCK_H_#define STOCK_H_#include<iostream>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 *co, long n = 0, double pr = 0.0);Stock(const Stock &);~Stock();void buy(long num, double price);void sell(long num, double price);void update(double price);const Stock & topval(const Stock & s)const;Stock & operator=(const Stock & s);friend ostream & operator<<(ostream & os,const Stock & s);};#endif
//stock.cpp#include<iostream>#include "stock.h"Stock::Stock(){company = new char[8];strcpy(company, "no name");shares = 0;share_val = 0.0;total_val = 0.0;}Stock::Stock(const char *co, long n, double pr){int len = strlen(co);company = new char[len + 1];strcpy(company, co);if (n < 0){cout << "Number of shares can't be negative; "<< company << " shares set to 0.\n";shares = 0;}elseshares = n;share_val = pr;set_tot();}Stock::Stock(const Stock & s){int len = strlen(s.company);company = new char[len + 1];strcpy(company, s.company);shares = s.shares;set_tot();}Stock::~Stock(){delete [] company;}void Stock::buy(long num, double price){if (num < 0){cout << "Number of shares purchased cannot 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 sold cannot be negative. " << "Transaction is aborted.\n";}else if (num > shares){cout << "You cannot 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;elsereturn *this;}Stock & Stock::operator=(const Stock & s){int len = strlen(s.company);company = new char[len + 1];strcpy(company, s.company);shares = s.shares;set_tot();return *this;}ostream & operator<<(ostream & os, const Stock & s){ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);streamsize prec = cout.precision(3);cout << "Company: " << s.company << " Shares: " << s.shares << '\n';cout << " Share Price: $" << s.share_val;cout.precision(2);cout << " Total Worth: $" << s.total_val << '\n';cout.setf(orig, ios_base::floatfield);cout.precision(prec);return os;}
//main.cpp#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)};cout << "Stock holdings:\n";int st;for (st = 0; st < STKS; st++){cout << stocks[st];}const Stock* top = &stocks[0];for (st = 1; st < STKS; st++){top = &top->topval(stocks[st]);}cout << "\nMost valuable holding:\n";cout << *top;cin.get();return 0;}

4.

//stack.h#ifndef STACK_H_#define STACK_H_typedef unsigned long Item;using namespace std;class Stack{private:enum{ MAX = 10 };Item * pitems;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);void showStack();Stack & operator=(const Stack & st);};#endif
//stack.cpp#include<iostream>#include "stack.h"Stack::Stack(int n){pitems = new Item[n];top = 0;size = n;}Stack::Stack(const Stack & st){pitems = new Item[st.size];top = st.top;size = st.size;for (int i = 0; i < top; i++)pitems[i] = st.pitems[i];}Stack::~Stack(){delete [] pitems;}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;cout << "push false" << endl;}}bool Stack::pop(Item & item){if (top <= 0){return false;cout << "pop false";}else{item = pitems[--top];return true;}}void Stack::showStack(){cout << "size: " << size << "  top: " << top << endl;}Stack & Stack::operator=(const Stack & st){if (this == &st)return *this;delete [] pitems;pitems = new Item[st.size];top = st.top;size = st.size;for (int i = 0; i < top; i++){pitems[i] = st.pitems[i];}return *this;}
//main.cpp#include <iostream>#include "stack.h"const int STKS = 4;int main(){Stack a(4);cout << a.isempty() << endl;a.push(5);a.push(6);a.push(7);a.push(8);a.push(9);cout << a.isfull() << endl;Stack b = a;b.showStack();for (int i = 0; i < 5; i++){Item s;a.pop(s);cout << s << endl;}b = a;b.showStack();cin.get();return 0;}

5. 程序见书 12.10,12.11,12.12。经测试在队列长度为10的时候,每小时到达的客户为19个时,平均等候时间大约为1分钟。

6.

//queue.h#ifndef QUEUE_H_#define QUEUE_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; 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);};#endif
//queue.cpp#include<cstdlib>#include "queue.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::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 (items == qsize)return false;Node *add = new Node;add->item = item;add->next = nullptr;items++;if (front == nullptr)front = add;elserear->next = add;rear = add;return true;}bool Queue::dequeue(Item &item){if (items == 0)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 = std::rand() % 3 + 1;arrive = when;}
//main.cpp#include <iostream>#include <cstdlib>#include <ctime>#include "queue.h"const int MIN_PER_HR = 60;bool newcustomer(double x);int main(){srand(time(0));cout << "Case Study: Bank of Heather Automatic Teller\n";cout << "Enter maximum size of queue: ";int qs;cin >> qs;Queue line1(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 cunstomers 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_time1 = 0;long wait_time2 = 0;long line_wait = 0;for (long cycle = 0; cycle < cyclelimit; cycle++){if (newcustomer(min_per_cust)){if (line1.isfull() && line2.isfull())turnaways++;else{customers++;temp.set(cycle);if (line1.queuecount() < line2.queuecount())line1.enqueue(temp);elseline2.enqueue(temp);}}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() + line2.queuecount()) / 2;}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";}elsecout << "No customers!\n";cout << "Done!\n";cin.get();cin.get();return 0;}bool newcustomer(double x) {return (rand()*x / RAND_MAX < 1);}
经测试,在两个队容量均为10的情况下,每小时到达的客户为51个时,平均等候时间约为1分钟。










0 0