第十二章编程练习答案

12.1依据下面类声明,完毕类。并编小程序使用它

//12.1依据下面类声明。完毕类,并编小程序使用它
#include <iostream>
#include <cstring>
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();void ShowCow() const;
};Cow::Cow(){}
Cow::Cow(const char * nm, const char * ho, double wt)
{strcpy(name,nm);hobby=new char[strlen(ho)+1];strcpy(hobby,ho);weight=wt;
}
Cow::Cow(const Cow & C)
{strcpy(name,C.name);hobby=new char[strlen(C.hobby)+1];strcpy(hobby,C.hobby);weight=C.weight;
}
Cow::~Cow() {delete [] hobby;}
void Cow::ShowCow() const
{cout << name << endl;cout << hobby << endl;cout << weight << endl;
}int main()
{Cow cow;Cow ccc("adads","dsdfsad",34);cow=ccc;cow.ShowCow();ccc.ShowCow();
}

12.2依据下面的主函数,编写类,使得:
a.重载+,使得两个字符串能够合并为一个
b.使用Stringlow()成员函数,使得字母能够转换为小写
c.使用Stringup()成员函数,使得字母可转换为大写
d.提供一个成员函数,使它返回一个char字符出现的个数

//12.2依据下面的主函数,编写类,使得:
//a.重载+,使得两个字符串能够合并为一个
//b.使用Stringlow()成员函数,使得字母能够转换为小写
//c.使用Stringup()成员函数,使得字母可转换为大写
//d.提供一个成员函数,使它返回一个char字符出现的个数
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;class String
{char*      mp_text;unsigned    m_text_length;void assignMember (const char* text){m_text_length = strlen(text);mp_text = new char [m_text_length + 1];strcpy(mp_text, text);}
public:static const unsigned    k_buffer_max_size = 256;const char* toCstr () const{return (mp_text);}String (const char* text = ""){assignMember(text);}String (const String& str){assignMember(str.toCstr());}~String (){delete [] mp_text;}unsigned getLength () const{return (m_text_length);}void stringup (){for (unsigned i = 0; i < m_text_length; ++i)mp_text[i] = (char)toupper(mp_text[i]);}void stringlow (){for (unsigned i = 0; i < m_text_length; ++i) mp_text[i] = (char)tolower((int)mp_text[i]);}unsigned has (char ch) const{unsigned  cnt = 0;for (unsigned i = 0; i < m_text_length; ++i)if (ch == mp_text[i])++cnt;return (cnt);}String& operator= (const String& str){if (&str == this)return (*this);delete [] mp_text;assignMember(str.toCstr());return (*this);}String & operator+= (const String& str){return (*this += str);}char& operator[] (unsigned idx){return (mp_text[idx]);}const char & operator[] (unsigned idx) const{return (mp_text[idx]);}friend ostream & operator<< (ostream& os, const String& str){os << str.toCstr();return (os);}friend istream & operator>> (istream& is, String& str){char  txt[k_buffer_max_size];if (is >> txt)str = txt;is.ignore(k_buffer_max_size, '\n');return (is);}friend bool operator< (const String& lvalue, const String& rvalue){return (strcmp(lvalue.toCstr(), rvalue.toCstr()) < 0);}friend bool operator> (const String& lvalue, const String& rvalue){return (rvalue < lvalue);}friend bool operator== (const String& lvalue, const String& rvalue){return (!(lvalue < rvalue) && !(lvalue > rvalue));}friend bool operator<= (const String& lvalue, const String& rvalue){return (!(lvalue > rvalue));}friend bool operator>= (const String& lvalue, const String& rvalue){return (!(lvalue < rvalue));}friend String operator+ (const String& lvalue, const String& rvalue){char* p_txt = new char [lvalue.getLength() + rvalue.getLength() + 1];strcpy(p_txt, lvalue.toCstr());strcat(p_txt, rvalue.toCstr());String    tmp(p_txt);delete [] p_txt;return (tmp);}
};int main()
{String s1(" and I am a C++ student.");String s2 = "Please enter your name: ";String s3;cout << s2;// overloaded << operatorcin >> s3;// overloaded >> operators2 = "My name is " + s3;// overloaded =, + operatorscout << s2 << ".\n";s2 = s2 + s1;s2.stringup();// converts string to uppercasecout  << "The string\n" << s2 << "\ncontains " << s2.has('A')<< " 'A' characters in it.\n";s1 = "red";// tstring(const char *),// then tstring & operator=(const string&)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();// converts string to lowercasefor (int i = 0; i < 3; i++){if (ans == rgb[i]) // overloaded == operator{cout << "That's right!\n";success = true;break;}}if (success)break;elsecout << "Try again!\n";}cout << "Bye" << endl;
}

12.3又一次编敲代码清单10.7,10.8。使用动态内存并重载<<取代show()

//12.3又一次编敲代码清单10.7,10.8,使用动态内存并重载<<取代show()
#include <iostream>
#include <cstring>
using namespace std;class Stock{char *company;int shares;double share_val;double total_val;void set_tot(){total_val=shares*share_val;};
public:Stock(){company=new char[8];strcpy(company,"no name");shares=0;share_val=0.0;total_val=0.0;}Stock(const char *co,long n=0,double pr=0){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"<<endl;shares=0;}elseshares=n;share_val=pr;set_tot();}~Stock(){delete []company;}void buy(long num,double price){if(num<0){cout<<"Number of shares purchase can't be negative."<<" Transaction is aborted."<<endl;}else{shares+=num;share_val=price;set_tot();}}void sell(long num,double price){if(num<0){cout<<"Number of shares sold can't be negative."<<"Transaction  is  aborted."<<endl;}else if(num>shares){cout<<"You can't sell more than you have!"<<"Transaction  is  aborted."<<endl;}else{shares-=num;share_val=price;set_tot();}}void update(double price){share_val=price;set_tot();}const Stock &topval(const Stock &s)const{if(s.total_val>total_val)return s;elsereturn *this;}friend ostream &operator<<(ostream &os,const Stock &s){ios_base::fmtflags orig=os.setf(ios_base::fixed,ios_base::floatfield);streamsize prec=os.precision(3);os<<"Company:"<<s.company<<"  Shares:"<<s.shares<<endl;os<<" Share Price:$"<<s.share_val;os.precision(2);os<<"    Total Worth:&"<<s.total_val<<endl;os.setf(orig,ios_base::floatfield);os.precision(prec);return os;}
};const int STKS = 4;
int main()
{
// create an array of initialized objectsStock 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];
// set pointer to first elementconst Stock * top = &stocks[0];for (st = 1; st < STKS; st++)top = &top->topval(stocks[st]);
// now top points to the most valuable holdingcout << "\nMost valuable holding:\n";cout << *top;return 0;
}

12.4按下面类声明,完毕类,并编写一个演示程序

//12.4按下面类声明,完毕类,并编写一个演示程序
#include <iostream>
using namespace std;
typedef unsigned long Item;class Stack{enum{MAX=10};Item * items;int size;int top;
public:Stack(int n=MAX){items=new Item [MAX];top=0;size=0;}Stack(const Stack &st){items=new Item[st.size];top=0;size=0;for(int i=0;i<st.size;i++){items[i]=st.items[i];size++;top++;}}~Stack(){delete [] items;}bool isEmpty(){return top==0;}bool isFull(){return top==MAX;}bool push(const Item &it){if(isFull())cout<<"error! Stack is full!"<<endl;else{items[top++]=it;size++;return true;}return false;}bool pop(Item &item){if(isEmpty())cout<<"error! Stack is empty!"<<endl;else{item=items[top--];size--;return true;}return false;}Stack & operator = (Stack &st){delete [] items;items=new Item[st.size];top=0;size=0;for(int i=0;i<st.size;i++){items[i]=st.items[i];size++;top++;}return (*this);}friend ostream & operator<<(ostream &os,const Stack & st){os<<"This Stack is:"<<endl;int len=st.top-1;while(len!=-1){cout<<st.items[len]<<endl;len--;}return os;}
};int main ()
{Stack s;Item it[20]={0};for(int i=0;i<11;i++){it[i]=i+1;s.push(it[i]);}cout<<s;Stack s1(s);cout<<"s1="<<s1;Stack s2=s;cout<<s;
}

12.5-12.6银行ATM顾客系统

// queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:long arrive;        // arrival time for customerint processtime;    // processing time for customer
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:
// class scope definitions// Node is a nested structure definition local to this classstruct Node { Item item; struct Node * next;};enum {Q_SIZE = 10};
// private class membersNode * front;       // pointer to front of QueueNode * rear;        // pointer to rear of Queueint items;          // current number of items in Queueconst int qsize;    // maximum number of items in Queue// preemptive definitions to prevent public copyingQueue(const Queue & q) : qsize(0) { }Queue & operator=(const Queue & q) { return *this;}
public:Queue(int qs = Q_SIZE); // create queue with a qs limit~Queue();bool isempty() const;bool isfull() const;int queuecount() const;bool enqueue(const Item &item); // add item to endbool dequeue(Item &item);       // remove item from front
};
#endif
// queue.cpp -- Queue and Customer methods
#include "queue.h"
#include <cstdlib>         // (or stdlib.h) for rand()// Queue methods
Queue::Queue(int qs) : qsize(qs)
{front = rear = NULL;    // or nullptritems = 0;
}Queue::~Queue()
{Node * temp;while (front != NULL)   // while queue is not yet empty{temp = front;       // save address of front itemfront = front->next;// reset pointer to next itemdelete temp;        // delete former front}
}bool Queue::isempty() const
{return items == 0;
}bool Queue::isfull() const
{return items == qsize;
}int Queue::queuecount() const
{return items;
}// Add item to queue
bool Queue::enqueue(const Item & item)
{if (isfull())return false;Node * add = new Node;  // create node
// on failure, new throws std::bad_alloc exceptionadd->item = item;       // set node pointersadd->next = NULL;       // or nullptr;items++;if (front == NULL)      // if queue is empty,front = add;        // place item at frontelserear->next = add;   // else place at rearrear = add;             // have rear point to new nodereturn true;
}// Place front item into item variable and remove from queue
bool Queue::dequeue(Item & item)
{if (front == NULL)return false;item = front->item;     // set item to first item in queueitems--;Node * temp = front;    // save location of first itemfront = front->next;    // reset front to next itemdelete temp;            // delete former first itemif (items == 0)rear = NULL;return true;
}// customer method// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{processtime = std::rand() % 3 + 1;arrive = when;
}
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime>   // for time()
#include "queue.h"
const int MIN_PER_HR = 60;bool newcustomer(double x); // is there a new customer?int main()
{using std::cin;using std::cout;using std::endl;using std::ios_base;
// setting things upstd::srand(std::time(0));    //  random initializing of rand()cout << "Case Study: Bank of Heather Automatic Teller\n";cout << "Enter maximum size of queue: ";int qs;cin >> qs;Queue line(qs);         // line queue holds up to qs peoplecout << "Enter the number of simulation hours: ";int hours;              //  hours of simulationcin >> hours;// simulation will run 1 cycle per minutelong cyclelimit = MIN_PER_HR * hours; // # of cyclescout << "Enter the average number of customers per hour: ";double perhour;         //  average # of arrival per hourcin >> perhour;double min_per_cust;    //  average time between arrivalsmin_per_cust = MIN_PER_HR / perhour;Item temp;              //  new customer datalong turnaways = 0;     //  turned away by full queuelong customers = 0;     //  joined the queuelong served = 0;        //  served during the simulationlong sum_line = 0;      //  cumulative line lengthint wait_time = 0;      //  time until autoteller is freelong line_wait = 0;     //  cumulative time in line// running the simulationfor (int cycle = 0; cycle < cyclelimit; cycle++){if (newcustomer(min_per_cust))  // have newcomer{if (line.isfull())turnaways++;else{customers++;temp.set(cycle);    // cycle = time of arrivalline.enqueue(temp); // add newcomer to line}}if (wait_time <= 0 && !line.isempty()){line.dequeue (temp);      // attend next customerwait_time = temp.ptime(); // for wait_time minutesline_wait += cycle - temp.when();served++;}if (wait_time > 0)wait_time--;sum_line += line.queuecount();}// reporting resultsif (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;
}//  x = average time, in minutes, between customers
//  return value is true if customer shows up this minute
bool newcustomer(double x)
{return (std::rand() * x / RAND_MAX < 1);
}

转载于:https://www.cnblogs.com/jzdwajue/p/7193866.html

c++ primer plus(第6版)中文版 第十二章编程练习答案相关推荐

  1. C++ Primer Plus 第六版(中文版)第十六章(重置版)编程练习答案

    //本博主所写的代码仅为阅读者提供参考: //若有不足之处请提出,博主会尽所能修改: //附上课后编程练习题目: //若是对您有用的话请点赞或分享提供给它人: //第3题的wordlist.txt文件 ...

  2. C Primer Plus(第六版)第十六章 编程练习答案

    距离上次隔了十二天,好像是有点慢,期间还看了下C++pp,看到句话,每章内容不是很多,建议一周内完成一章,虽然之后要看琢石成器,C++也要顺带看一下.--11.16 CH16 Code answer ...

  3. C语言程序设计现代方法(第二版)十二章编程题答案

    作为一名C语言初学者,以下答案为随手练习笔记,均已通过编译器实现书上功能,如有错误之处欢迎指出. 1. (a) # include <cstdio> # include <iostr ...

  4. Netty In Action中文版 - 第十二章:SPDY

    Netty In Action中文版 - 第十二章:SPDY 本章我将不会直接翻译Netty In Action书中的原文,感觉原书中本章讲的很多废话,我翻译起来也吃力.所以,本章内容我会根据其他资料 ...

  5. 记录——《C Primer Plus (第五版)》第十二章编程练习第1-8题

    1.不使用全局变量,重写12.4的程序 . # include <stdio.h>int critic(void); int main(void) {int units = 0;print ...

  6. c++primer(第五版) 第十五章 面向对象程序设计习题答案

    纯原创    转载请注明出处:http://blog.csdn.net/axuan_k 略过书上有现成代码的题目 15.1  15.2 15.1 虚成员是基类中的概念 基类中的某些函数希望它的派生类能 ...

  7. C Primer Plus 6th(中文版)第六章编程练习答案

    **3.**使用嵌套循环,按下面的格式打印字母: F FE FED FEDC FEDCB FEDCBA #include<stdio.h>int main(void) {char str[ ...

  8. 鸟哥的Linux私房菜基础学习篇(第二版)第十二章课后习题与答案

    习题: 1.我想要知道某个档案里面含有 boot 的字眼,而这个档案在 /etc/ 底下,我要如何找出这个档案? 答:既然知道有这个字眼那就好办了!可以直接下达: grep boot /etc/* 2 ...

  9. 【课后习题】高等数学第七版下第十二章 无穷级数 第二节 常数项级数的审敛法

    习题12-2 1. 用比较审敛法或极限形式的比较审敛法判定下列级数的收敛性: (1) 1+13+15+⋯+1(2n−1)+⋯1+\frac{1}{3}+\frac{1}{5}+\cdots+\frac ...

  10. python程序设计第三版约翰策勒第六章编程练习答案

    第一题 def lrc(animal, call):m()print("And on his farm he had a {0}, Ee I Ee I Oh!".format(an ...

最新文章

  1. 热评一箩筐——《黑客攻防技术宝典》
  2. 【转载】一行代码加载网络图片到ImageView——Android Picasso
  3. 【实用/转载】ALV OO Container屏幕自适应设置
  4. Linux学习:shell 命令(压缩包管理)
  5. matlab过滤,matlab过滤问题
  6. 端口隔离配置命令、端口镜像(抓包配置)详解(附图,建议PC观看)
  7. 机器学习中常见的距离公式
  8. 审计风险控制流程的起点_【经验分享】审计整改流程体系的优化措施
  9. 动态ip软件win7_IPXE+ISCSI Target安装WIN7
  10. linux常用命令(3)——系统管理1
  11. 从零到实现Shiro中Authorization和Authentication的缓存
  12. 如何获取iOS应用网络权限?
  13. 英语4级的分数如何计算机,英语四级的分数是怎么计算的?
  14. 泰拉瑞亚试图加载不正确的_泰拉瑞亚Switch中文版将在12月19日发售|宝可梦 剑/盾大量细节公布 自动存档可关经验平均分配等...
  15. 人人的互联网时代——读娱乐致死和未来是湿的
  16. 考公 | 粉笔网课笔记——数量 刘凯
  17. 获取天气预报ajax,Ajax 通过城市名获取数据(全国天气预报API)
  18. 001 A Comprehensive Survey of Privacy-preserving Federated Learning(便于寻找:FedAvg、垂直联邦学习的基本步骤)
  19. 标准盒模型与怪异盒模型
  20. 白盒测试与黑盒测试的定义与区别

热门文章

  1. esxi 需要整合 空间不足_太炫酷了!10月微信新花样!微信情侣空间怎么设置如何弄微信情侣空间在哪里开...
  2. c语言创建若干个成绩栏目,2015年计算机二级《C语言》考试上机测试题(6)
  3. 每日一题(开开森森学前端之Object系列)
  4. andriod搭建自己的轮询框架
  5. docker commit新镜像之后删除旧镜像
  6. 关于Spring Cloud Config服务器介绍
  7. 在C7000+VMware vSphere5.5环境中的基础架构服务器部署实例
  8. Puppet常用资源使用详解
  9. 一起talk C栗子吧(第二十七回:C语言实例--插入排序)
  10. vagrant 错误记录