博客内容经历了一次整理,以前发的博文太散、没什么水准,搞的随笔分类越来越多orz,这次把CPP这本书的课后练习的程序代码放到一起方便查阅与修改。。嗯

9.6.1

#ifndef _9..1_H_
#define _9.6.1_H_ #include <iostream>
#include <cstring> const int Len = ;
struct golf
{
char fullname[Len];
int handicap;
}; //non-interactive version
//function sets golf structure to provided name, handicap
//using values passed as arguments to the function
void setgolf(golf & g, const char * name, int hc); //interactive version
//function solicits name and handicap fron user
//and sets the members of g to the values entered
//return 1 if name is enterd, 0 if name is empty string
int setgolf(golf & g); //function resets handicap to new value
void handicap(golf & g, int hc); //function displays contents of golf structure
void showgolf(const golf & g); #endif
#include "9.6.1.h"

void setgolf(golf & g, const char * name, int hc)
{
memcpy(g.fullname, name, Len);
g.handicap = hc;
} int setgolf(golf & g)
{
char str[Len] = "";
int hc = ; std::cout << "Enter the name : ";
std::cin.getline(str,Len); //会接受空格、回车、TAB等空字符串 if(str[] == '\0')
{
return ;
}
std::cout << "Enter the handicap : ";
std::cin >> hc;
std::cin.get(); //接收掉上一次输入丢下的回车字符 setgolf(g, str, hc); return ;
} void handicap(golf & g, int hc)
{
g.handicap = hc;
} void showgolf(const golf & g)
{
std::cout << "Name : " << g.fullname << std::endl;
std::cout << "Handicap : " << g.handicap << std::endl << std::endl;
}
#include "9.6.1.h"

int main(void)
{
golf g[]; for(int i = ; i < ; i++)
{
if(setgolf(g[i]) == )
{
std::cout << "End input!" << std::endl;
break;
}
showgolf(g[i]);
}
if(g[].fullname[] != '\0')
{
handicap(g[], );
showgolf(g[]);
} return ;
}

9.6.2

#include <iostream>
#include <string>
const int ArSize = ; void strcount(const std::string & str)
{
using namespace std;
static int total = ;
int count = ; cout << "\"" << str << "\" contains ";
count += str.length();
total += count;
cout << count << " characters\n";
cout << total << " characters total\n";
} int main()
{
using namespace std;
string input; cout << "Enter a line:\n";
getline(cin, input);
while(input != "")
{
strcount(input);
cout << "Enter next line (empty line to quit):\n";
getline(cin, input);
}
cout << "Bye\n";
return ;
}

9.6.3

#include <iostream>
#include <cstring>
using namespace std; struct chaff
{
char dross[];
int slag;
}; void fun1()
{
const int BUF = ;
char buffer[BUF];
chaff * p = new (buffer) chaff[]; // do not delete strcpy(p->dross, "PingGe");
p[].slag = ; strcpy(p[].dross, "Hello");
p[].slag = ; for(int i = ; i < ; i++)
{
cout << &p[i] << " : " << p[i].dross << " : " << p[i].slag << endl;
}
} void fun2()
{
const int BUF = ;
char * buffer = new char[BUF]; // must delete chaff * p = new (buffer) chaff[]; strcpy(p[].dross, "PingGe");
p[].slag = ; strcpy(p[].dross, "Hello");
p[].slag = ; for(int i = ; i < ; i++)
{
cout << &p[i] << " : " << p[i].dross << " : " << p[i].slag << endl;
} delete [] buffer;
} int main()
{
fun1();
fun2(); return ;
}

9.6.4

#ifndef _9..4_H_
#define _9.6.4_H_ #include <iostream>
#include <algorithm> namespace SALES
{
const int QUARTERS = ;
struct Sales
{
double sales[QUARTERS];
double average;
double max;
double min;
};
//copies the lesser of 4 or n items from the array ar
//to the sales member of s and computes and stores the
//average, maximum, and minimum values of the enterd items;
//remaining elements of sales, if any, set to 0
void setSales(Sales & s, const double ar[], int n); //gathers sales for 4 quarters interactively, stores them
//in the sales member of s and computes and stores the
//average, maximum, and minimum values
void setSales(Sales & s); //display all information in structure s
void showSales(const Sales & s);
} #endif
#include "9.6.4.h"

namespace SALES
{
void setSales(Sales & s, const double ar[], int n)
{
double sum = 0.0; for(int i = ; i < n; i++)
{
s.sales[i] = ar[i];
sum += ar[i];
}
for(int i = n; i < QUARTERS; i++)
{
s.sales[i] = ;
}
s.average = sum / n; //STL求最大值算法,返回的是指针- -
s.max = *std::max_element(s.sales, s.sales + n);
s.min = *std::min_element(s.sales, s.sales + n);
} void setSales(Sales & s)
{
double sum = 0.0; std::cout << "Input the " << QUARTERS << " number" << std::endl; for(int i = ; i < QUARTERS; i++)
{
std::cin >> s.sales[i];
sum += s.sales[i];
}
s.average = sum / QUARTERS; //STL求最大值算法,返回的是指针- -
s.max = *std::max_element(s.sales, s.sales + QUARTERS);
s.min = *std::min_element(s.sales, s.sales + QUARTERS);
} void showSales(const Sales & s)
{
std::cout << "Sales : ";
for(int i = ; i < QUARTERS; i++)
{
std::cout << s.sales[i] << " ";
} std::cout << std::endl << "Average : " << s.average << std::endl;
std::cout << "Max : " << s.max << std::endl;
std::cout << "Min : " << s.min << std::endl;
}
}
#include "9.6.4.h"

int main(void)
{
SALES::Sales a, b; SALES::setSales(a);
SALES::showSales(a);
std::cout << std::endl; double ar[] = {1.23, 3.5, , };
SALES::setSales(b, ar, );
SALES::showSales(b); return ;
}

10.10.1

#ifndef _10..1_H_
#define _10.10.1_H_ #include <iostream>
#include <string> class BankAccount
{
private:
std::string name;
std::string acctnum;
double balance; public:
BankAccount(const std::string & client, const std::string & num, double bal = 0.0);
void show(void) const;
void deposit(double cash);
void withdraw(double cash);
}; #endif
#include "10.10.1.h"

BankAccount::BankAccount(const std::string & client, const std::string & num, double bal)
{
name = client;
acctnum = num;
balance = bal;
} void BankAccount::show(void) const
{
std::cout << "Name : " << name << std::endl;
std::cout << "Acctnum : " << acctnum << std::endl; //Store original flags
std::streamsize prec = std::cout.precision();
std::ios_base::fmtflags orig = std::cout.setf(std::ios_base::fixed); std::cout << "Money : " << balance << std::endl << std::endl;; //Reset to stored values
std::cout.setf(orig, std::ios_base::floatfield);
std::cout.precision(prec);
} void BankAccount::deposit(double cash)
{
if(cash <= )
{
std::cerr << "Error : money must >0!" << std::endl;
}
else
{
balance += cash;
}
} void BankAccount::withdraw(double cash)
{
if(cash <= )
{
std::cerr << "Error : money must >0!" << std::endl;
}
else if(balance - cash < )
{
std::cerr << "Error : you can only take out : " << balance << "$" << std::endl;
}
else
{
balance -= cash;
}
}
#include "10.10.1.h"

int main(void)
{
BankAccount pingge("PingGe", "", ); pingge.show(); pingge.deposit();
pingge.show(); pingge.deposit(-);
pingge.show(); pingge.withdraw();
pingge.show(); pingge.withdraw();
pingge.show(); return ;
}

10.10.2

#ifndef _10..2_H_
#define _10.10.2_H_ #include <string>
#include <iostream> class Person
{
private:
static const int LIMIT = ;
std::string lname; //Person's last name
char fname[LIMIT]; //Person's first name public:
Person(); //#1
Person(const std::string & ln, const char * fn = "Heyyou"); //#2 //The following methods display lname and fname
void Show(void) const; //firstname lastname format
void FormalShow(void) const; //lastname firstname format
}; #endif
#include "10.10.2.h"
#include <cstring> Person::Person()
{
lname = "";
fname[] = '\0';
} Person::Person(const std::string & ln, const char * fn)
{
lname = ln;
memcpy(fname, fn, LIMIT);
} void Person::Show(void) const
{
std::cout << "Firstname : " << fname << std::endl;
std::cout << "Lastname : " << lname << std::endl;
} void Person::FormalShow(void) const
{
std::cout << "Lastname : " << lname << std::endl;
std::cout << "Firstname : " << fname << std::endl;
}
#include "10.10.2.h"

int main(void)
{
Person one;
Person two("Smythecraft");
Person three = Person("Dimwiddy", "Sam"); one.Show();
one.FormalShow(); two.Show();
two.FormalShow(); three.Show();
three.FormalShow(); return ;
}

10.10.3

#ifndef _10..3_H_
#define _10.10.3_H_ #include <string>
#include <cstring>
#include <iostream> class golf
{
private:
std::string fullname;
int handicap_; public:
golf(); golf(const std::string & name, int hc); ~golf(); void handicap(int hc); void showgolf(void) const;
}; #endif
#include "10.10.3.h"

golf::golf()
{
std::cout << "Enter the name : ";
std::cin >> this->fullname; std::cout << "Enter the handicap : ";
std::cin >> this->handicap_;
} golf::golf(const std::string & name, int hc)
{
fullname = name;
handicap_ = hc;
} golf::~golf()
{
std::cout << "Call ~golf" << std::endl;
} void golf::handicap(int hc)
{
handicap_ = hc;
} void golf::showgolf(void) const
{
std::cout << "Name : " << fullname << std::endl;
std::cout << "Handicap : " << handicap_ << std::endl;
}
#include "10.10.3.h"

int main(void)
{
(golf()).showgolf(); golf p = golf("pingge", );
p.showgolf(); golf q;
q.showgolf(); golf r("fuck", );
r.showgolf();
return ;
}

10.10.4

#ifndef _10..4_H_
#define _10.10.4_H_ #include <iostream>
#include <algorithm> namespace SALES
{
class Sales
{
private:
//enum{QUARTERS = 4};
static const int QUARTERS = ;
double sales[QUARTERS],
average,
max,
min; public:
//copies the lesser of 4 or n items from the array ar
//to the sales member of s and computes and stores the
//average, maximum, and minimum values of the enterd items;
//remaining elements of sales, if any, set to 0
Sales(const double ar[], int n); //gathers sales for 4 quarters interactively, stores them
//in the sales member of s and computes and stores the
//average, maximum, and minimum values
Sales(); //display all information in structure s
void showSales(void) const;
};
} #endif
#include "10.10.4.h"

namespace SALES
{
Sales::Sales()
{
std::cout << "Input the " << QUARTERS << " number" << std::endl; double sum = 0.0; for(int i = ; i < QUARTERS; i++)
{
std::cin >> sales[i];
sum += sales[i];
}
average = sum / QUARTERS; //STL求最大值算法,返回的是指针- -
max = *std::max_element(sales, sales + QUARTERS);
min = *std::min_element(sales, sales + QUARTERS);
} Sales::Sales(const double ar[], int n)
{
double sum = 0.0; for(int i = ; i < n; i++)
{
sales[i] = ar[i];
sum += ar[i];
}
for(int i = n; i < QUARTERS; i++)
{
sales[i] = ;
}
average = sum / n; //STL求最大值算法,返回的是指针- -
max = *std::max_element(sales, sales + n);
min = *std::min_element(sales, sales + n);
} void Sales::showSales(void) const
{
std::cout << "Sales : ";
for(int i = ; i < QUARTERS; i++)
{
std::cout << sales[i] << " ";
} std::cout << std::endl << "Average : " << average << std::endl;
std::cout << "Max : " << max << std::endl;
std::cout << "Min : " << min << std::endl;
}
}
#include "10.10.4.h"

int main(void)
{
SALES::Sales a;
a.showSales(); double ar[] = {1.23, 3.5, , };
SALES::Sales b(ar, );
b.showSales(); return ;
}

10.10.5

#ifndef _10..5_H_
#define _10.10.5_H_ struct customer
{
char fullname[];
double payment;
}; typedef customer Item; class Stack
{
private:
enum {MAX = }; //constant specific to class
Item items[MAX]; //holds stack items
int top; //index for top stack item public:
Stack();
bool isempty() const;
bool isfull() const; //add item to stack
//push() returns false if stack already is full, true otherwise
bool push(const Item & item); //pop top into item
//pop() returns false if stack already is empty, true otherwise
bool pop(Item & item);
}; #endif
#include "10.10.5.h"

Stack::Stack()
{
top = ;
} bool Stack::isempty() const
{
return top == ;
} bool Stack::isfull() const
{
return top == MAX;
} bool Stack::push(const Item & item)
{
if(top < MAX)
{
items[top++] = item;
return true;
}
else
{
return false;
}
} bool Stack::pop(Item & item)
{
if(top > )
{
item = items[--top];
return true;
}
else
{
return false;
}
}
#include <iostream>
#include "10.10.5.h" int main(void)
{
Item a{"pingge", };
Item b; Stack st; while(st.push(a) == true); while(st.pop(b) == true )
{
std::cout << b.fullname << b.payment << std::endl;
}
return ;
}

10.10.6

#ifndef _10..6_H_
#define _10.10.6_H_ #include <iostream> class Move
{
private:
double x;
double y; public:
Move(double a = , double b = ); //Sets x, y to a, b
void showmove(void) const; //Shows current x, y values //This function adds x of m to x of invoking object to get new x,
//adds y of m to y of invoking object to get new y, creates a new
//move object initialized to new x, y values and returns it
Move add(const Move & m) const; void reset(double a = , double b = ); //Resets x, y to a, b
}; #endif
#include "10.10.6.h"

Move::Move(double a, double b)
{
x = a;
y = b;
} void Move::showmove(void) const
{
std::cout << "X : " << x << std::endl;
std::cout << "Y : " << y << std::endl;
} Move Move::add(const Move & m) const
{
Move new_object = Move(x + m.x, y + m.y);
return new_object;
} void Move::reset(double a, double b)
{
x = a;
y = b;
}
#include "10.10.6.h"

int main()
{
Move a(1.23, 4.56);
a.showmove(); (a.add(Move(, ))).showmove(); a.reset();
a.showmove();
return ;
}

10.10.8

#ifndef _10..7_H_
#define _10.10.7_H_ #include <iostream>
#include <string> struct node
{
std::string name;
int money;
}; typedef node Item; class List
{
private:
struct NODE
{
Item data;
struct NODE * last;
struct NODE * next;
};
NODE *head, *p; unsigned long Length; public:
List();
~List();
void Add(const Item & item);
unsigned long Size(void) const;
void Clear(void);
bool Empty(void) const;
Item & Front(void) const;
Item & Back(void) const;
void Visit(void(*pf)(Item &));
}; #endif
#include "10.10.8.h"

List::List()
{
head = new NODE; head->last = head->next = head; p = NULL; Length = ;
} List::~List()
{
NODE *q = NULL;
for(p = head->next; p->next != head; p = q)
{
q = p->next;
delete p;
}
delete head;
} void List::Add(const Item & item)
{
p = new NODE;
p->data = item; p->last = head->last;
p->last->next = p;
p->next = head;
head->last = p; Length++;
} unsigned long List::Size(void) const
{
return Length;
} void List::Clear(void)
{
NODE *q = NULL;
for(p = head->next; p != head; p = q)
{
q = p->next;
delete p;
} head->last = head->next = head; p = NULL; Length = ;
} bool List::Empty(void) const
{
if(head->next == head)
{
return true;
}
else
{
return false;
}
} Item & List::Front(void) const
{
return head->next->data;
} Item & List::Back(void) const
{
return head->last->data;
} void List::Visit(void (*pf)(Item &))
{
for(p = head->next; p != head; p = p->next)
{
(*pf)(p->data);
}
}
#include "10.10.8.h"

void Show(const Item & item)
{
std::cout << "Name : " << item.name << std::endl;
std::cout << "Money : " << item.money << std::endl << std::endl;
} void Operate(Item & item)
{
item.money += ;
} int main()
{
Item a{"PingGe", },
b{"Ass", -}; List list;
std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
std::cout << "List length : " << list.Size() << std::endl; //1add
std::cout << std::endl << "Begin Add" << std::endl;;
list.Add(a);
std::cout << "Front of the list : " << std::endl; Show(list.Front());
std::cout << "Back of the list : " << std::endl; Show(list.Back());
std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
std::cout << "List length : " << list.Size() << std::endl; //2add
std::cout << std::endl << "Next Add" << std::endl;;
list.Add(b);
std::cout << "Front of the list : " << std::endl; Show(list.Front());
std::cout << "Back of the list : " << std::endl; Show(list.Back());
std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
std::cout << "List length : " << list.Size() << std::endl; //3operate +10
std::cout << std::endl << "Call operate" << std::endl;;
list.Visit(&Operate);
std::cout << "Front of the list : " << std::endl; Show(list.Front());
std::cout << "Back of the list : " << std::endl; Show(list.Back());
std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
std::cout << "List length : " << list.Size() << std::endl; //4clear
std::cout << std::endl << "Call clear" << std::endl;;
list.Clear();
//std::cout << "Front of the list : " << std::endl; Show(list.Front());
//std::cout << "Back of the list : " << std::endl; Show(list.Back());
std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
std::cout << "List length : " << list.Size() << std::endl; return ;
}

11.9.1

#ifndef _11..1_H_
#define _11.9.1_H_
#include <iostream>
namespace VECTOR
{
class Vector
{
public:
enum Mode{RECT,POL}; //RECT for rectangular, POL for Polar modes private:
double x; //horizontal value
double y; //vertical value
double mag; //length of vectot
double ang; //direction of vector in degrees
Mode mode; //RECT or POL //private methods for setting values
void set_mag(void);
void set_ang(void);
void set_x(void);
void set_y(void); public:
Vector();
Vector(double n1, double n2, Mode form = RECT);
void reset(double n1, double n2, Mode form = RECT);
~Vector();
double xval(void) const {return x;} //return x value
double yval(void) const {return y;} //return y value
double magval(void) const {return mag;} //return magnitude
double angval(void) const {return ang;} //return angle
void polar_mode(void); //set mode to POL
void rect_mode(void); //set mode to RECT //operator overloading
Vector operator+(const Vector & b) const;
Vector operator-(const Vector & b) const;
Vector operator-(void) const;
Vector operator*(double n) const; //friends
friend Vector operator*(double n, const Vector & a);
friend std::ostream & operator<<(std::ostream & os, const Vector & v);
};
}//end namespace VECTOR
#endif
#include <cmath>
#include "11.9.1.h" using std::sqrt;
using std::sin;
using std::cos;
using std::atan;
using std::atan2;
using std::cout; namespace VECTOR
{
//compute degrees in one radian
//should be about 57.2957795130823
const double Rad_to_deg = 45.0 / atan(1.0); //private methods
//calculates magnitude from x and y
void Vector::set_mag(void)
{
mag = sqrt(x * x + y * y);
} void Vector::set_ang(void)
{
if(x == 0.0 && y == 0.0)
{
ang = 0.0;
}
else
{
ang = atan2(y, x);
}
} //set x from polar coordinate
void Vector::set_x(void)
{
x = mag * cos(ang);
} //set y from polar coordinate
void Vector::set_y(void)
{
y = mag * sin(ang);
} //public methods
//default constructor
Vector::Vector()
{
x = y = mag = ang = 0.0;
mode = RECT;
} //construct vector from rectangular coordinates if form is r
//(the default) or else from polar coordinates if form is p
Vector::Vector(double n1, double n2, Mode form)
{
mode = form;
if(form == RECT)
{
x = n1;
y = n2;
set_mag();
set_ang();
}
else if(form == POL)
{
mag = n1;
ang = n2 / Rad_to_deg;
set_x(); set_y();
}
else
{
cout << "Incorrect 3rd argument to Vector() -- ";
cout << "vector set to 0\n";
x = y = mag = ang = 0.0;
mode = RECT;
}
} //reset vector from rectangular coordinates if form is
//RECT (the default) or else from polar coordinates if
//form is POL
void Vector::reset(double n1, double n2, Mode form)
{
mode = form;
if(form == RECT)
{
x = n1;
y = n2;
set_mag();
set_ang();
}
else if(form == POL)
{
mag = n1;
ang = n2 / Rad_to_deg;
set_x();
set_y();
}
else
{
cout << "Incorrect 3rd argument to Vector() -- ";
cout << "vector set to 0\n";
x = y = mag = ang = 0.0;
mode = RECT;
}
} Vector::~Vector() //destructor
{ } void Vector::polar_mode(void) //set to polar mode
{
mode = POL;
} void Vector::rect_mode(void) //set to rectangular mode
{
mode = RECT;
} //operator overloading
//add two Vectors
Vector Vector::operator+(const Vector & b) const
{
return Vector(x + b.x, y + b.y);
} //subtract Vector b from a
Vector Vector::operator-(const Vector & b) const
{
return Vector(x - b.x, y - b.y);
} //reverse sign of Vector
Vector Vector::operator-(void) const
{
return Vector(-x, -y);
} //multiply vector by n
Vector Vector::operator*(double n) const
{
return Vector(n * x, n * y);
} //friend methods
//mutiply n by Vector a
Vector operator*(double n, const Vector & a)
{
return a * n;
} //display rectangular coordinates if mode is RECT
//else display polar coordinates if mode is POL
std::ostream & operator<<(std::ostream & os, const Vector & v)
{
if(v.mode == Vector::RECT)
{
os << "(x, y) = (" << v.x << ", " << v.y << ")";
}
else if(v.mode == Vector::POL)
{
os << "(m, a) = (" << v.mag << ", " << v.ang * Rad_to_deg << ")";
}
else
{
os << "vector object mode is invalid";
}
return os;
}
}//end namespace VECTOR
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "11.9.1.h" int main(void)
{
using namespace std;
using VECTOR::Vector; srand(time()); //seed random-number generator ofstream fout;
fout.open("text.txt"); //open the file double direction;
Vector step;
Vector result(0.0, 0.0);
unsigned long steps = ;
double target;
double dstep; cout << "Enter target distance (q to quit) : ";
while(cin >> target)
{
cout << "Enter step length : ";
if(!(cin >> dstep))
{
break;
}
fout << "Target Distance : " << target << ", " << "Step Size : " << dstep << endl; fout << steps << " : " << result << endl;
while(result.magval() < target)
{
direction = rand() % ;
step.reset(dstep, direction, Vector::POL);
result = result + step;
//result += step;
steps++; fout << steps << " : " << result << endl;
}
fout << "After " << steps << " steps, the subject had the following location : " << endl;;
fout << result << endl;
result.polar_mode();
fout << " or\n" << result << endl;
fout << "Averager outward distance per step = " << result.magval() / steps << endl;
steps = ;
result.reset(0.0, 0.0);
cout << "Enter target distance (q to quit) : ";
}
cout << "Bye!\n";
return ;
}

11.9.5

#ifndef _11..5_H_
#define _11.9.5_H_ class Stonewt
{
public:
enum Mode{STONE, INTPOUND, FLOATPOUND};
private:
enum {Lbs_per_stn = };
int stone;
double pds_left;
double pounds;
Mode mode; public:
Stonewt(double lbs, Mode mode_ = FLOATPOUND);
Stonewt(int stn, double lbs, Mode mode_ = FLOATPOUND);
Stonewt(Mode mode_ = FLOATPOUND);
~Stonewt(); //operator overloading
Stonewt operator+(const Stonewt & st) const;
Stonewt operator-(const Stonewt & st) const;
Stonewt operator*(const double n) const; //friends
friend Stonewt operator*(const double n, const Stonewt & st);
friend std::ostream & operator<<(std::ostream & os, const Stonewt & st);
}; #endif
#include <iostream>
#include "11.9.5.h"
using std::cout;
using std::endl; Stonewt::Stonewt(double lbs, Mode mode_)
{
mode = mode_;
stone = int(lbs) / Lbs_per_stn;
pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
} Stonewt::Stonewt(int stn, double lbs, Mode mode_)
{
mode = mode_;
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
} Stonewt::Stonewt(Mode mode_)
{
mode = mode_;
stone = pounds = pds_left = ;
} Stonewt::~Stonewt()
{ } Stonewt Stonewt::operator+(const Stonewt & st) const
{
return Stonewt(pounds + st.pounds);
} Stonewt Stonewt::operator-(const Stonewt & st) const
{
return Stonewt(pounds - st.pounds);
} Stonewt Stonewt::operator*(const double n) const
{
return Stonewt(pounds * n);
} Stonewt operator*(const double n, const Stonewt & st)
{
return st * n;
} std::ostream & operator<<(std::ostream & os, const Stonewt & st)
{
if(st.mode == Stonewt::STONE)
{
os << st.stone << " stone, " << st.pds_left << " pounds";
}
else if(st.mode == Stonewt::INTPOUND)
{
os << (int)(st.pounds + 0.5) << " pounds";
}
else if(st.mode == Stonewt::FLOATPOUND)
{
os << st.pounds << " pounds";
}
else
{
os << "Error";
}
return os;
}
#include <iostream>
#include "11.9.5.h"
using std::cout;
using std::endl; void display(const Stonewt & st, int n)
{
for(int i = ; i < n; i++)
{
cout << "Wow! ";
cout<<st;
}
} int main()
{
Stonewt incognito = ;
Stonewt wolfe(285.7, Stonewt::STONE);
Stonewt taft(, , Stonewt::STONE); cout << "The celebrity weight ";
cout << incognito << endl;
cout << "The detective weight ";
cout << wolfe << endl;
cout << "The President weight ";
cout << taft << endl; incognito = 276.8;
taft = ;
cout << "After dinner, the celebrity weight ";
cout << incognito << endl;
cout << "After dinner, the President weight ";
cout << taft << endl;
display(taft, );
cout << "The wrestler weighed even more.\n";
display(, );
cout << "No stone left unearned\n"; cout << endl << "TEST the operator : " << endl;
cout << "incognito : " << incognito << endl;
cout << "wolfe : " << wolfe << endl;
cout << "taft : " << taft << endl; cout << "incognito + wolfe = " << incognito + wolfe << endl;
cout << "taft - incognito = " << taft - incognito << endl;
cout << "taft * 2 = " << taft * << endl << "2 * taft := " << * taft << endl; return ;
}

11.9.6

#ifndef _11..6_H_
#define _11.9.6_H_ class Stonewt
{
public:
enum Mode{STONE, INTPOUND, FLOATPOUND};
private:
enum {Lbs_per_stn = };
int stone;
double pds_left;
double pounds;
Mode mode; public:
Stonewt(double lbs, Mode mode_ = FLOATPOUND);
Stonewt(int stn, double lbs, Mode mode_ = FLOATPOUND);
Stonewt(Mode mode_ = FLOATPOUND);
~Stonewt(); //operator overloading
Stonewt operator+(const Stonewt & st) const;
Stonewt operator-(const Stonewt & st) const;
Stonewt operator*(const double n) const;
bool operator==(const Stonewt & st) const;
bool operator!=(const Stonewt & st) const;
bool operator>(const Stonewt & st) const;
bool operator>=(const Stonewt & st) const;
bool operator<(const Stonewt & st) const;
bool operator<=(const Stonewt & st) const; //friends
friend Stonewt operator*(const double n, const Stonewt & st);
friend std::ostream & operator<<(std::ostream & os, const Stonewt & st);
friend std::istream & operator>>(std::istream & is, Stonewt & st);
}; #endif
#include <iostream>
#include "11.9.6.h"
using std::cout;
using std::endl; Stonewt::Stonewt(double lbs, Mode mode_)
{
mode = mode_;
stone = int(lbs) / Lbs_per_stn;
pds_left = int(lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
} Stonewt::Stonewt(int stn, double lbs, Mode mode_)
{
mode = mode_;
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
} Stonewt::Stonewt(Mode mode_)
{
mode = mode_;
stone = pounds = pds_left = ;
} Stonewt::~Stonewt()
{ } //operator overloading
Stonewt Stonewt::operator+(const Stonewt & st) const
{
return Stonewt(pounds + st.pounds);
} Stonewt Stonewt::operator-(const Stonewt & st) const
{
return Stonewt(pounds - st.pounds);
} Stonewt Stonewt::operator*(const double n) const
{
return Stonewt(pounds * n);
} bool Stonewt::operator==(const Stonewt & st) const
{
if(pounds == st.pounds)
{
return true;
}
else
{
return false;
}
} bool Stonewt::operator!=(const Stonewt & st) const
{
if(pounds != st.pounds)
{
return true;
}
else
{
return false;
}
} bool Stonewt::operator>(const Stonewt & st) const
{
if(pounds > st.pounds)
{
return true;
}
else
{
return false;
}
} bool Stonewt::operator>=(const Stonewt & st) const
{
if(pounds >= st.pounds)
{
return true;
}
else
{
return false;
}
} bool Stonewt::operator<(const Stonewt & st) const
{
if(pounds < st.pounds)
{
return true;
}
else
{
return false;
}
} bool Stonewt::operator<=(const Stonewt & st) const
{
if(pounds <= st.pounds)
{
return true;
}
else
{
return false;
}
} //friends
Stonewt operator*(const double n, const Stonewt & st)
{
return st * n;
} std::ostream & operator<<(std::ostream & os, const Stonewt & st)
{
if(st.mode == Stonewt::STONE)
{
os << st.stone << " stone, " << st.pds_left << " pounds";
}
else if(st.mode == Stonewt::INTPOUND)
{
os << (int)(st.pounds + 0.5) << " pounds";
}
else if(st.mode == Stonewt::FLOATPOUND)
{
os << st.pounds << " pounds";
}
else
{
os << "Error";
}
return os;
} std::istream & operator>>(std::istream & is, Stonewt & st)
{
double n;
is >> n;
st = Stonewt(n);
return is;
}
#include <iostream>
#include "11.9.6.h"
using std::cin;
using std::cout;
using std::endl; int main()
{
Stonewt st[] = {{},
{285.7, Stonewt::FLOATPOUND},
{, , Stonewt::FLOATPOUND}}; cout << "Input the other three pounds : ";
for(int i = ; i < ; i++)
{
cin >> st[ + i];
}
cout << "Show : " << endl;
for(int i = ; i < ; i++)
{
cout << st[i] << endl;
} const Stonewt * p_max, * p_min;
p_max = p_min = &st[];
for(int i = ; i < ; i++)
{
p_max = *p_max>st[i] ? p_max : &st[i];
p_min = *p_min<st[i] ? p_min : &st[i];
}
cout << "MAX : " << *p_max << endl;
cout << "MIN : " << *p_min << endl; Stonewt st_11(, );
int n = ;
for(int i = ; i < ; i++)
{
st[i] >= st_11 ? n++ : ;
}
cout << "ANS : " << n << endl; return ;
}

11.9.7

#ifndef _11..7_H_
#define _11.9.7_H_ #include <iostream> class Complex
{
private:
double a, b; public:
Complex();
Complex(double a_, double b_); //operator overloading
Complex operator+(const Complex & c) const;
Complex operator-(const Complex & c) const;
Complex operator*(const Complex & c) const;
Complex operator~(void) const; //firends
friend Complex operator*(const Complex & c, double x); friend Complex operator*(double x, const Complex & c);
friend std::ostream & operator<<(std::ostream & os, const Complex & c);
friend std::istream & operator>>(std::istream & is, Complex & c);
}; #endif
#include "11.9.7.h"

Complex::Complex()
{
a = b = 0.0;
} Complex::Complex(double a_, double b_)
{
a = a_;
b = b_;
} Complex Complex::operator+(const Complex & c) const
{
return Complex(a + c.a, b + c.b);
} Complex Complex::operator-(const Complex & c) const
{
return Complex(a - c.a, b - c.b);
}
Complex Complex::operator*(const Complex & c) const
{
return Complex(a * c.a - b * c.b, a * c.b + b * c.a);
} Complex Complex::operator~(void) const
{
return Complex(a, -b);
} Complex operator*(const Complex & c, double x)
{
return Complex(x * c.a, x * c.b);
} Complex operator*(double x, const Complex & c)
{
return Complex(x * c.a, x * c.b);
} std::ostream & operator<<(std::ostream & os, const Complex & c)
{
os << "(" << c.a << ", " << c.b << "i)";
return os;
} std::istream & operator>>(std::istream & is, Complex & c)
{
std::cout << "real : ";
is >> c.a;
std::cout << "imaginary : ";
is >> c.b; return is;
}
#include "11.9.7.h"
using namespace std; int main(void)
{
Complex a(3.0, 4.0);
Complex c;
cout << "Enter a complex number (q to quit) : " << endl;
while(cin >> c)
{
cout << "c is " << c << endl;
cout << "complex conjugate is " << ~c << endl;
cout << "a is " << a << endl; cout << "a + c is " << a + c << endl;
cout << "a - c is " << a - c << endl;
cout << "a * c is " << a * c << endl;
cout << "2 * c is " << * c << endl;
cout << "Enter a complex number (q to quit) : " << endl;
}
cout << "Done!" << endl; return ;
}

12.10.1

#ifndef _COW_H_
#define _COW_H_ class Cow
{
private:
char name[];
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(void) const; //display all cow data
}; #endif
#include "12.10.1.h"
#include <iostream>
#include <cstring> Cow::Cow()
{
name[] = '\0';
//hobby = NULL;
hobby = new char[];
hobby[] = '\0';
weight = ;
} Cow::Cow(const char * nm, const char * ho, double wt)
{
strcpy(name, nm);
hobby = new char[strlen(ho) + ];
strcpy(hobby, ho);
weight = wt;
} Cow::Cow(const Cow & c)
{
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + ];
strcpy(hobby, c.hobby);
weight = c.weight;
} Cow::~Cow()
{
std::cout << "Call ~Cow!" << std::endl;
delete [] hobby;
} Cow & Cow::operator=(const Cow & c)
{
if(this == &c)
{
return *this;
} strcpy(name, c.name);
delete [] hobby;
hobby = new char[strlen(c.hobby) + ];
strcpy(hobby, c.hobby);
weight = c.weight; return *this;
} void Cow::ShowCow(void) const
{
std::cout << "Name : " << name << std::endl;
std::cout << "Hobby : " << hobby << " : " << &hobby << std::endl;
std::cout << "Weight : " << weight << std::endl;
}
#include "12.10.1.h"

int main(void)
{
{
Cow c1;
Cow c2("PingGe", "Watch TV", );
Cow c3(c2);
Cow c4 = c3; c1.ShowCow(); c2.ShowCow();
c3.ShowCow();
c4.ShowCow();
}
return ;
}

12.10.2

#ifndef _12..2_H_
#define _12.10.2_H_ #include <iostream> class String
{
private:
char * str; //pointer to string
int len; //length of string
static int num_strings; //number of objects
static const int CINLIM = ; //cin input limit public:
//constructors and other methods
String(const char * s); //constructor
String(); //default constructor
String(const String & st); //copy constructor
~String(); //destructor
int length(void) const {return len;} //overloaded operator methods
String & operator=(const String & st);
String & operator=(const char * s);
char & operator[](int i);
const char & operator[](int i) const; //overloaded operator friends
friend bool operator<(const String & st1, const String & st2);
friend bool operator>(const String & st1, const String & st2);
friend bool operator==(const String & st1, const String & st2);
friend std::ostream & operator<<(std::ostream & os, const String & st);
friend std::istream & operator>>(std::istream & is, String & st); //new methods
friend String operator+(const String & st1, const String & st2);
void Stringlow(void);
void Stringup(void);
int has(const char & ch) const; //static function
static int HowMany(void);
}; #endif
#include <cstring>
#include <cctype>
#include "12.10.2.h" //initializing static class member
int String::num_strings = ; //static method
int String::HowMany(void)
{
return num_strings;
} //class methods
String::String(const char * s)
{
len = std::strlen(s);
str = new char[len + ];
std::strcpy(str, s);
num_strings++;
} String::String()
{
len = ;
str = new char[];
str[] = '\0';
num_strings++;
} String::String(const String & st)
{
num_strings++;
len = st.len;
str = new char[len + ];
std::strcpy(str, st.str);
} String::~String()
{
--num_strings;
delete [] str;
} //overloaded operator methods
//assign a String to a string
String & String::operator=(const String & st)
{
if(this == &st)
{
return *this;
}
delete [] str;
len = st.len;
str = new char[len + ];
std::strcpy(str, st.str);
return *this;
} //assign a C string to a String
String & String::operator=(const char * s)
{
delete [] str;
len = std::strlen(s);
str = new char[len + ];
std::strcpy(str, s);
return *this;
} //read-write char access for non-const string
char & String::operator[](int i)
{
return str[i];
} //read-only char access for const String
const char & String::operator[](int i) const
{
return str[i];
} //overliaded operator friends
bool operator<(const String & st1, const String & st2)
{
return (std::strcmp(st1.str, st2.str) < );
} 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) == );
} //simple String output_iterator_tag
std::ostream & operator<<(std::ostream & os, const String & st)
{
os << st.str;
return os;
} std::istream & operator>>(std::istream & is, String & st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if(is)
{
st = temp;
}
while(is && is.get() != '\n'); return is;
} String operator+(const String & st1, const String & st2)
{
char * s = new char[st1.len + st2.len + ];
strcpy(s, st1.str);
strcat(s, st2.str); String add(s);
delete [] s; return add;
} void String::Stringlow(void)
{
for(int i = ; i < len; i++)
{
str[i] = std::tolower(str[i]);
}
} void String::Stringup(void)
{
for(int i = ; i < len; i++)
{
str[i] = std::toupper(str[i]);
}
} int String::has(const char & ch) const
{
int n = ;
for(int i = ; i < len; i++)
{
if(str[i] == ch)
{
n++;
}
}
return n;
}
#include <iostream>
#include "12.10.2.h"
using namespace std; int main(void)
{
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[] = {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 = ; i < ; 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 ;
}

12.10.3

#ifndef _12..3_H_
#define _12.10.3_H_ class Stock
{
private:
char * company;
int shares;
double share_val;
double total_val;
void set_tot(void)
{
total_val = shares * share_val;
} public:
Stock();
Stock(const char * s, long n = , double pr = 0.0);
Stock(const Stock & st);
~Stock();
void buy(long num, double price);
void sell(long num, double price);
void updata(double price);
const Stock & topval(const Stock & st) const;
Stock & operator=(const Stock & st);
friend std::ostream & operator<<(std::ostream & os, const Stock & st);
}; #endif
#include <iostream>
#include <cstring>
#include "12.10.3.h" Stock::Stock()
{
company = new char[];
company[] = '\0';
shares = ;
share_val = 0.0;
total_val = 0.0;
} Stock::Stock(const char * s, long n, double pr)
{
company = new char[strlen(s) + ];
strcpy(company, s);
if(n < )
{
std::cout << "Number of shares can't be negative; " << company << " shares set to0.\n";
shares = ;
}
else
{
shares = n;
}
share_val = pr;
set_tot();
} Stock::Stock(const Stock & st)
{
company = new char[strlen(st.company) + ];
strcpy(company, st.company);
shares = st.shares;
share_val = st.share_val;
total_val = st.total_val;
} Stock::~Stock()
{
delete [] company;
} void Stock::buy(long num, double price)
{
if(num < )
{
std::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 < )
{
std::cout << "Number of shares sold can't be negative. " << "Transaction is aborted.\n";
}
else if(num > shares)
{
std::cout << "You can't sell more than you have! " << "Transaction is aborted.\n";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
} void Stock::updata(double price)
{
share_val = price;
set_tot();
} const Stock & Stock::topval(const Stock & st) const
{
if(st.total_val > total_val)
{
return st;
}
else
{
return *this;
}
} Stock & Stock::operator=(const Stock & st)
{
if(this == &st)
{
return *this;
}
delete [] company;
company = new char[strlen(st.company) + ];
strcpy(company, st.company);
shares = st.shares;
share_val = st.share_val;
total_val = st.total_val;
} std::ostream & operator<<(std::ostream & os, const Stock & st)
{
std::ios_base::fmtflags orig = os.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::streamsize prec = os.precision(); os << "Company : " << st.company << " Shares : " << st.shares << std::endl;
os << " Share Price : $" << st.share_val; os.precision();
os << " Total Worth : $" << st.total_val << std::endl; os.setf(orig, std::ios_base::floatfield);
os.precision(prec); return os;
}
#include <iostream>
#include "12.10.3.h" const int STKS = ;
int main(void)
{
Stock stocks[STKS] = {
Stock("NanoSmart", , 20.0),
Stock("Boffo Objects", , 2.0),
Stock("Monolithic Obelisks", , 3.25),
Stock("Fleep Enterprises", , 6.5)
}; Stock st1(stocks[]);
std::cout << st1;
Stock st2 = stocks[];
std::cout << st2; std::cout << "\nStock holdings : \n";
int st;
for(st = ; st < STKS; st++)
{
std::cout << stocks[st];
} const Stock * top = &stocks[];
for(st = ; st < STKS; st++)
{
top = &top->topval(stocks[st]);
}
std::cout << "\nMost valuable holding : \n" << *top; return ;
}

12.10.4

#ifndef _12..4_H_
#define _12.10.4_H_ typedef unsigned long Item; class Stack
{
private:
enum{MAX = }; //constant specific to class
Item * pitems; //holds stack items
int size; //number of elements in stack
int top; //index for top stack item public:
Stack(int n = MAX); //creates stack with n elements
Stack(const Stack & st);
~Stack();
bool isempty(void) const;
bool isfull(void) const; //push() returns false if stack already is full, true otherwise
bool push(const Item & item); //add item to stack //pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); //pop top into item Stack & operator=(const Stack & st);
}; #endif
#include <iostream>
#include <cstring>
#include "12.10.4.h" Stack::Stack(int n)
{
pitems = new Item[n];
size = n;
top = ;
} Stack::Stack(const Stack & st)
{
pitems = new Item[st.size];
std::memcpy(pitems, st.pitems, st.size * sizeof(Item));
size = st.size;
top = st.top;
} Stack::~Stack()
{
delete [] pitems;
} bool Stack::isempty(void) const
{
return (top == );
} bool Stack::isfull(void) const
{
return (top == size);
} bool Stack::push(const Item & item)
{
if(top < size)
{
pitems[top++] = item;
return true;
}
else
{
return false;
}
} bool Stack::pop(Item & item)
{
if(top > )
{
item = pitems[--top];
return true;
}
else
{
return false;
}
} Stack & Stack::operator=(const Stack & st)
{
if(this == &st)
{
return *this;
} delete [] pitems;
pitems = new Item[st.size];
std::memcpy(pitems, st.pitems, st.size * sizeof(Item)); size = st.size;
top = st.top; return *this;
}
#include <iostream>
#include "12.10.4.h"
using namespace std; int main(void)
{
Stack st1(); for(int i = ; i < ; i++)
{
st1.push(i);
} Stack st2(st1);
Stack st3 = st2; Item item;
while(!st1.isempty())
{
st1.pop(item);
cout << item;
}
st1.~Stack();
cout << endl; while(!st2.isempty())
{
st2.pop(item);
cout << item;
}
st2.~Stack();
cout << endl; while(!st3.isempty())
{
st3.pop(item);
cout << item;
} return ;
}

12.10.6

#ifndef _12..5_H_
#define _12.10.5_H_ class Customer
{
public:
Customer()
{
arrive = processtime = ;
}
void set(long when); long when(void) const
{
return arrive;
}
int ptime(void) const
{
return processtime;
} private:
long arrive; //arrival time for customer
int processtime; //processing time for customer
}; typedef Customer Item; class Queue
{
public:
Queue(int qs = Q_SIZE); //create queue with a qs limit
~Queue();
bool isempty(void) const;
bool isfull(void) const;
int queuecount(void) const;
bool enqueue(const Item & item); //add item to end
bool dequeue(Item & item); //remove item from front private:
enum{Q_SIZE = };
//Node is anested structure definition local to this class
struct Node
{
Item item;
struct Node * next;
}; Node * front; //pointer to front of Queue
Node * rear; //pointer to rear of Queue
int items; //current number of items in Queue
const int qsize; //maxinum number of items in Queue //preemptive definitions to prevent public copying
Queue(const Queue & q) : qsize() {}
Queue & operator=(const Queue & q) {return *this;}
}; #endif
#include <iostream>
#include <cstdlib>
#include "12.10.5.h" Queue::Queue(int qs) : qsize(qs)
{
front = rear = NULL;
items = ;
} Queue::~Queue()
{
Node * temp;
while(front != NULL)
{
temp = front;
front = front->next;
delete temp;
}
} bool Queue::isempty(void) const
{
return items == ;
} bool Queue::isfull(void) const
{
return items == qsize;
} int Queue::queuecount(void) const
{
return items;
} bool Queue::enqueue(const Item & item)
{
if(isfull())
{
return false;
}
Node * add = new Node; //create node add->item = item; //set node pointers
add->next = NULL;
items++; if(front == NULL) //if queue is empty
{
front = add;
}
else //else placr at rear
{
rear->next = add;
}
rear = add;
return true;
} bool Queue::dequeue(Item & item)
{
if(front == NULL)
{
return false;
}
item = front->item; //set item to first item in queue
items--; Node * temp = front; //save location of first item
front = front->next; //reset front to next item
delete temp; //delete former first item if(items == )
{
rear = NULL;
}
return true;
} void Customer::set(long when)
{
processtime = std::rand() % + ;
arrive = when;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "12.10.5.h"
using namespace std; const int MIN_PER_HR = ; //x = average time, in minutes, between customers
//return value is true if customer shows up this minute
bool newcustomer(double x) //is there a new customer?
{
return (rand() * x / RAND_MAX < );
} int main(void)
{
//setting things up
srand(time()); //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[2] = {Queue(qs), Queue(qs)}; //line queue holds up to qs people
Queue line_1(qs), line_2(qs); cout << "Enter the number of simulation hours : ";
int hours; //hours of simulation
cin >> hours;
//simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; //# of cycles cout << "Enter the average number of customers per hour : ";
double perhour; //average # of arrival per hour cin >> perhour;
double min_per_cust; //average time between arrivals
min_per_cust = MIN_PER_HR / perhour; Item temp[]; //new customer data
long turnaways = ; //turned away by full queue
long customers = ; //joined the queue
long served = ; //served during the simulation
long sum_line = ; //cumulative line length
int wait_time[] = {}; //time until autoteller is free
long line_wait = ; //cumulative time in line //running the simulation
for(int cycle = ; cycle < cyclelimit; cycle++)
{
if(newcustomer(min_per_cust)) //have newcomer
{
if(line_1.isfull() && line_2.isfull())
{
turnaways++;
}
else if(line_1.queuecount() < line_2.queuecount())
{
customers++;
temp[].set(cycle); //cycle = time of arrival
line_1.enqueue(temp[]); //add newcomer to line
}
else
{
customers++;
temp[].set(cycle); //cycle = time of arrival
line_2.enqueue(temp[]); //add newcomer to line
}
} if(wait_time[] <= && !line_1.isempty())
{
line_1.dequeue(temp[]); //attend next customer
wait_time[] = temp[].ptime(); //for wait_time minutes
line_wait += cycle - temp[].when();
served++;
}
if(wait_time[] <= && !line_2.isempty())
{
line_2.dequeue(temp[]); //attend next customer
wait_time[] = temp[].ptime(); //for wait_time minutes
line_wait += cycle - temp[].when();
served++;
} if(wait_time[] > )
{
wait_time[]--;
}
if(wait_time[] > )
{
wait_time[]--;
}
sum_line += (line_1.queuecount() + line_2.queuecount());
} //reporting results
if(customers > )
{
cout << "Customers accepted : " << customers << endl;
cout << " customers served : " << served << endl;
cout << " turnaways : " << turnaways << endl;
cout << "average queue size : ";
cout.precision();
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << (double) sum_line / cyclelimit / << endl;
cout << "average wait time : " << (double)line_wait / served << " minutes\n";
}
else
{
cout << "No customers!\n";
}
cout << "Done!\n"; return ;
}

13.11.1

#ifndef _13..1_H_
#define _13.11.1_H_ //base class
class Cd //represents a CD disk
{
private:
char performers[];
char label[];
int selections; //number of selection
double playtime; //playing time in minutes public: Cd(char * s1, char * s2, int n, double x);
Cd();
virtual ~Cd() {};
virtual void Report(void) const; //reports all CD data
}; class Classic : public Cd
{
private:
char fav[]; public:
Classic(char * f, char * s1, char * s2, int n, double x);
Classic(char * f, const Cd & cd);
Classic();
virtual ~Classic() {};
virtual void Report(void) const; //reports all CD data & Classic data
}; #endif
#include <iostream>
#include <cstring>
#include "13.11.1.h" //Cd methods
Cd::Cd(char * s1, char * s2, int n, double x)
{
std::strcpy(performers, s1);
std::strcpy(label, s2);
selections = n;
playtime = x;
} Cd::Cd()
{
performers[] = '\0';
label[] = '\0';
selections = ;
playtime = ;
} void Cd::Report(void) const
{
std::cout << "Performers : " << performers << std::endl;
std::cout << "Label : " << label << std::endl;
std::cout << "Selections : " << selections << std::endl;
std::cout << "Playtime : " << playtime << std::endl;
} //Classic methods
Classic::Classic(char * f, char * s1, char * s2, int n, double x) : Cd(s1, s2, n, x)
{
std::strcpy(fav, f);
} Classic::Classic(char * f, const Cd & cd) : Cd(cd)
{
std::strcpy(fav, f);
} Classic::Classic() : Cd()
{
fav[] = '\0';
} void Classic::Report(void) const
{
Cd::Report();
std::cout << "Favourite : " << fav << std::endl;
}
#include <iostream>
#include "13.11.1.h" using namespace std; void Bravo(const Cd & disk)
{
disk.Report();
} int main(void)
{
Cd c1("Beatles", "Capitol", , 35.5);
Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philips", , 57.17); Cd * pcd = &c1; cout << "Using object directly : \n";
c1.Report(); //use Cd method
c2.Report(); //use Classic method
cout << endl; cout << "Using type cd * pointer to objects : \n";
pcd->Report(); //use Cd method for cd object
pcd = &c2;
pcd->Report(); //use Classic method for classic object
cout << endl; cout << "Calling a function with a Cd reference argument : \n";
Bravo(c1);
Bravo(c2);
cout << endl; cout << "Testing assignment : \n";
Classic copy;
copy = c2;
copy.Report();
cout << endl; return ;
}

13.11.2

#ifndef _13..2_H_
#define _13.11.2_H_ //base class
class Cd //represents a CD disk
{
private:
char * performers;
char * label;
int selections; //number of selection
double playtime; //playing time in minutes public:
Cd(char * s1, char * s2, int n, double x);
Cd(const Cd & d);
Cd();
virtual ~Cd();
virtual void Report(void) const; //reports all CD data
Cd & operator=(const Cd & d);
}; class Classic : public Cd
{
private:
char * fav; public:
Classic(char * f, char * s1, char * s2, int n, double x);
Classic(char * f, const Cd & cd);
Classic(const Classic & c);
Classic();
virtual ~Classic();
virtual void Report(void) const; //reports all CD data & Classic data
Classic & operator=(const Classic & c);
}; #endif
#include <iostream>
#include <cstring>
#include "13.11.2.h" //Cd methods
Cd::Cd(char * s1, char * s2, int n, double x)
{
performers = new char[std::strlen(s1) + ];
label = new char[std::strlen(s2) + ]; std::strcpy(performers, s1);
std::strcpy(label, s2); selections = n;
playtime = x;
} Cd::Cd(const Cd & d)
{
performers = new char[std::strlen(d.performers) + ];
label = new char[std::strlen(d.label) + ]; std::strcpy(performers, d.performers);
std::strcpy(label, d.label); selections = d.selections;
playtime = d.playtime;
} Cd::Cd()
{
performers = NULL;
label = NULL; selections = ;
playtime = ;
} Cd::~Cd()
{
delete [] performers;
delete [] label;
} void Cd::Report(void) const
{
std::cout << "Performers : " << performers << std::endl;
std::cout << "Label : " << label << std::endl;
std::cout << "Selections : " << selections << std::endl;
std::cout << "Playtime : " << playtime << std::endl;
} Cd & Cd::operator=(const Cd & d)
{
if(this == &d)
{
return *this;
} delete [] performers;
delete [] label; performers = new char[std::strlen(d.performers) + ];
label = new char[std::strlen(d.label) + ]; std::strcpy(performers, d.performers);
std::strcpy(label, d.label); selections = d.selections;
playtime = d.playtime; return * this;
} //Classic methods
Classic::Classic(char * f, char * s1, char * s2, int n, double x) : Cd(s1, s2, n, x)
{
fav = new char[std::strlen(f) + ];
std::strcpy(fav, f);
} Classic::Classic(char * f, const Cd & cd) : Cd(cd)
{
fav = new char[std::strlen(f) + ];
std::strcpy(fav, f);
} Classic::Classic(const Classic & c) : Cd(c)
{
fav = new char[std::strlen(c.fav) + ];
std::strcpy(fav, c.fav);
} Classic::Classic() : Cd()
{
fav = NULL;
} Classic::~Classic()
{
delete [] fav;
} void Classic::Report(void) const
{
Cd::Report();
std::cout << "Favourite : " << fav << std::endl;
} Classic & Classic::operator=(const Classic & c)
{
if(this == &c)
{
return *this;
} delete [] fav; Cd::operator=((const Cd &)c); fav = new char[std::strlen(c.fav) + ];
std::strcpy(fav, c.fav); return * this;
}
#include <iostream>
#include "13.11.2.h" using namespace std; void Bravo(const Cd & disk)
{
disk.Report();
} int main(void)
{
Cd c1("Beatles", "Capitol", , 35.5);
Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philips", , 57.17); Cd * pcd = &c1; cout << "Using object directly : \n";
c1.Report(); //use Cd method
c2.Report(); //use Classic method
cout << endl; cout << "Using type cd * pointer to objects : \n";
pcd->Report(); //use Cd method for cd object
pcd = &c2;
pcd->Report(); //use Classic method for classic object
cout << endl; cout << "Calling a function with a Cd reference argument : \n";
Bravo(c1);
Bravo(c2);
cout << endl; cout << "Testing assignment : \n";
Classic copy;
copy = c2;
copy.Report();
cout << endl; return ;
}

13.11.3

#ifndef _DMA_H_
#define _DMA_H_ #include <iostream> //Base ABC Class Using DMA
class ABC
{
private:
char * label;
int rating; public:
ABC(const char * l = "null", int r = );
ABC(const ABC & a);
ABC & operator=(const ABC & a); virtual ~ABC();
virtual void View(void) const = ;
}; //derived class with DMA
class baseDMA : public ABC
{
public:
baseDMA(const char * l = "null", int r = ) : ABC(l, r) {}
baseDMA(const baseDMA & rs) : ABC(rs) {}
virtual ~baseDMA() {}
baseDMA & operator=(const baseDMA & rs)
{
ABC::operator=(rs);
return * this;
} virtual void View(void) const;
}; //derived class without DMA
//no destructor needed
//uses implicit copy constructor
//uses implicit assignment operator
class lacksDMA : public ABC
{
private:
enum{COL_LEN = };
char color[COL_LEN]; public:
lacksDMA(const char * c = "blank", const char * l = "null", int r = );
lacksDMA(const char * c, const baseDMA & rs);
virtual ~lacksDMA() {} virtual void View(void) const;
}; //derived class with DMA
class hasDMA : public ABC
{
private:
char * style; public:
hasDMA(const char * s = "none", const char * l = "null", int r = );
hasDMA(const char * s, const baseDMA & rs);
hasDMA(const hasDMA & hs);
virtual ~hasDMA();
hasDMA & operator=(const hasDMA & hs); virtual void View(void) const;
}; #endif // _DMA_H_
#include <iostream>
#include <cstring>
#include "13.11.3.h" //ABC methods
ABC::ABC(const char * l, int r)
{
label = new char[std::strlen(l) + ];
std::strcpy(label, l); rating = r;
} ABC::ABC(const ABC & a)
{
label = new char[std::strlen(a.label) + ];
std::strcpy(label, a.label); rating = a.rating;
} ABC & ABC::operator=(const ABC & a)
{
if(this == &a)
{
return *this;
}
delete [] label; label = new char[std::strlen(a.label) + ]; std::strcpy(label, a.label); rating = a.rating; return * this;
} ABC::~ABC()
{
delete [] label;
} void ABC::View(void) const
{
std::cout << "Label : " << label << std::endl;
std::cout << "rating : " << rating << std::endl;
} //baseDMA methods
void baseDMA::View(void) const
{
ABC::View();
} //lacksDMA methods
lacksDMA::lacksDMA(const char * c, const char * l, int r) : ABC(l, r)
{
std::strcpy(color, c);
} lacksDMA::lacksDMA(const char * c, const baseDMA & rs) : ABC(rs)
{
std::strcpy(color, c);
} void lacksDMA::View(void) const
{
ABC::View();
std::cout << "Color : " << color << std::endl;
} //hasDMA methods
hasDMA::hasDMA(const char * s, const char * l, int r) : ABC(l, r)
{
style = new char[std::strlen(s) + ];
std::strcpy(style, s);
} hasDMA::hasDMA(const char * s, const baseDMA & rs) : ABC(rs)
{
style = new char[std::strlen(s) + ];
std::strcpy(style, s);
} hasDMA::hasDMA(const hasDMA & hs) : ABC(hs)
{
style = new char[std::strlen(hs.style) + ];
std::strcpy(style, hs.style);
} hasDMA::~hasDMA()
{
delete [] style;
} hasDMA & hasDMA::operator=(const hasDMA & hs)
{
if(this == &hs)
{
return *this;
}
ABC::operator=( dynamic_cast<const ABC &>(hs) ); delete [] style; style = new char[std::strlen(hs.style) + ]; std::strcpy(style, hs.style); return * this;
} void hasDMA::View(void) const
{
ABC::View();
std::cout << "Style : " << style << std::endl;
}
#include <iostream>
#include <string>
#include "13.11.3.h" using namespace std; const int N = ;
int main(void)
{
ABC * p_DMA[N]; char label[];
int tempnum;
char kind; for(int i = ; i < N; i++)
{
cout << "Enter label : ";
//getline(cin, temp);
cin >> label; cout << "Enter rating : ";
cin >> tempnum; cout << "Enter 1 for baseDMA or 2 for lacksDMA or 3 for hasDMA : ";
while(cin >> kind && (kind != '' && kind != '' && kind != ''))
{
cout << "Enter either 1 or 2 or 3 : ";
} switch(kind)
{
case '':
{
p_DMA[i] = new baseDMA(label, tempnum);
}
break; case '':
{
char color[];
cout << "Enter color : ";
//getline(cin, color);
cin >> color;
p_DMA[i] = new lacksDMA(color, label, tempnum);
}
break; case '':
{
char style[];
cout << "Enter style : ";
//getline(cin, style);
cin >> style;
p_DMA[i] = new hasDMA(style, label, tempnum);
}
break; default : break;
}
while(cin.get() != '\n')
{
continue;
}
} for(int i = ; i < N; i++)
{
p_DMA[i]->View();
cout << endl;
} for(int i = ; i < N; i++)
{
delete p_DMA[i];
} return ;
}

13.11.4

#ifndef _13..4_H_
#define _13.11.4_H_ #include <iostream> class Port
{
private:
char * brand;
char style[]; //i.e., tawny, ruby,vintage
int bottles; public:
Port(const char * br = "none", const char * st = "none", int b = );
Port(const Port & p);
virtual ~Port()
{
delete [] brand;
}
Port & operator=(const Port & p);
Port & operator+=(int b); //adds b to bottles
Port & operator-=(int b); //subtracts b from bottles, if available int BottleCount(void) const
{
return bottles;
}
virtual void Show(void) const;
friend std::ostream & operator<<(std::ostream & os, const Port & p);
}; class VintagePort : public Port //style necessarily = "vintage"
{
private:
char * nickname; //i.e.,"The Noble" or "Old Velvet", etc.
int year; //vintage year public:
VintagePort();
VintagePort(const char * br, int b, const char * nn, int y);
VintagePort(const VintagePort & vp);
~VintagePort()
{
delete [] nickname;
}
VintagePort & operator=(const VintagePort & vp);
virtual void Show(void) const;
friend std::ostream & operator<<(std::ostream & os, const VintagePort & vp);
}; #endif
#include <iostream>
#include <cstring>
#include "13.11.4.h" //Port methods
Port::Port(const char * br, const char * st, int b)
{
brand = new char[std::strlen(br) + ];
std::strcpy(brand, br); std::strcpy(style, st); bottles = b;
} Port::Port(const Port & p)
{
brand = new char[std::strlen(p.brand) + ];
std::strcpy(brand, p.brand); std::strcpy(style, p.style); bottles = p.bottles;
} Port & Port::operator=(const Port & p)
{
if(this == &p)
{
return * this;
}
delete [] brand; brand = new char[std::strlen(p.brand) + ]; std::strcpy(brand, p.brand);
std::strcpy(style, p.style); bottles = p.bottles; return * this;
} Port & Port::operator+=(int b)
{
bottles += b; return * this;
} Port & Port::operator-=(int b)
{
if(bottles - b >= )
{
bottles -= b;
}
else
{
std::cout << "Can't subtract " << b << " from bottles!" << std::endl;
} return * this;
} void Port::Show(void) const
{
std::cout << "Brand: " << brand << std::endl;
std::cout << "Kind: " << style << std::endl;
std::cout << "Bottles: " << bottles << std::endl;
} std::ostream & operator<<(std::ostream & os, const Port & p)
{
os << p.brand << ", " << p.style << ", " << p.bottles; return os;
} //VintagePort methods
VintagePort::VintagePort() : Port()
{
nickname = new char[];
std::strcpy(nickname, "none");
year = ;
} VintagePort::VintagePort(const char * br, int b, const char * nn, int y) : Port(br, "none", b)
{
nickname = new char[std::strlen(nn) + ];
std::strcpy(nickname, nn); year = y;
} VintagePort::VintagePort(const VintagePort & vp) : Port(vp)
{
nickname = new char[std::strlen(vp.nickname) + ];
std::strcpy(nickname, vp.nickname); year = vp.year;
} VintagePort & VintagePort::operator=(const VintagePort & vp)
{
if(this == &vp)
{
return * this;
}
Port::operator=(vp); delete [] nickname; nickname = new char[std::strlen(vp.nickname) + ];
std::strcpy(nickname, vp.nickname); year = vp.year; return * this;
} void VintagePort::Show(void) const
{
Port::Show();
std::cout << "Nickname: " << nickname << std::endl;
std::cout << "Year: " << year << std::endl;
} std::ostream & operator<<(std::ostream & os, const VintagePort & vp)
{
os << (const Port &)vp;
os << ", " << vp.nickname << ", " << vp.year; return os;
}
#include <iostream>
#include "13.11.4.h" using namespace std; int main(void)
{
Port p1;
p1.Show();
cout << p1 << endl << endl; Port p2("Gallo", "tawny", );
p1 = p2;
cout << p1 << endl << endl; VintagePort vp1("Gallo", , "Old velvet", );
vp1.Show();
cout << endl; Port * p;
p = &p1;
p->Show();
cout << endl; p = &vp1;
p->Show();
cout << endl; vp1 += ;
vp1.Show();
cout << endl; vp1 -= ;
vp1.Show();
cout << endl; return ;
}

15.8.1

#ifndef _15..1_H_
#define _15.8.1_H_ class Remote;
class Tv
{
friend class Remote; // Remote can access Tv private parts
public:
void changemode(Remote & r); public:
enum {Off, On};
enum {MinVal, MaxVal = };
enum {Antenna, Cable};
enum {TV, DVD}; Tv(int s = Off, int mc = ) : state(s), volume(), maxchannel(mc), channel(), mode(Cable), input(TV) {}
void onoff() {state ^= ;}
bool ison() const {return state == On;}
bool volup();
bool voldown();
void chanup();
void chandown();
void set_mode() {mode = (mode == Antenna) ? Cable : Antenna;}
void set_input() {input = (input == TV) ? DVD : TV;}
void settings() const; // display all settings
private:
int state; // on or off
int volume; // assumed to be digitized
int maxchannel; // maximum number of channels
int channel; // current channel setting
int mode; // boardcast or cable
int input; // TV or DVD
};
class Remote
{
friend class Tv;
private:
int mode; // controls TV or DVD
int normal;
public:
Remote(int m = Tv::TV) : mode(m) {}
bool volup(Tv & t) {return t.volup();}
bool voldown(Tv& t) {return t.voldown();}
void onoff(Tv & t) {t.onoff();}
void chanup(Tv & t) {t.chanup();}
void chandown(Tv & t) {t.chandown();}
void set_chan(Tv & t, int c) {t.channel = c;}
void set_mode(Tv & t) {t.set_mode();}
void set_input(Tv & t) {t.set_input();} void showmode() {std::cout << "ModeofTv : " << (normal ? "Normal" : "Interact") << std::endl;}
}; #endif
#include <iostream>
#include "15.8.1.h" void Tv::changemode(Remote & r)
{
if(state == On)
{
r.normal ^= ;
}
} bool Tv::volup()
{
if(volume < MaxVal)
{
volume++;
return true;
}
else
{
return false;
}
} bool Tv::voldown()
{
if(volume > MaxVal)
{
volume--;
return true;
}
else
{
return false;
}
} void Tv::chanup()
{
if(channel < maxchannel)
{
channel++;
}
else
{
channel = ;
}
} void Tv::chandown()
{
if(channel > )
{
channel--;
}
else
{
channel = maxchannel;
}
} void Tv::settings() const
{
using std::cout;
using std::endl; cout << "TV is " << (state == Off ? "Off" : "On") << endl;
if(state == On)
{
cout << "Volume setting = " << volume << endl;
cout << "Channel setting = " << channel << endl;
cout << "Mode = " << (mode == Antenna ? "antenna" : "cable") << endl;
cout << "Input = " << (input == TV ? "TV" : "DVD") << endl; }
}
#include <iostream>
#include "15.8.1.h" int main()
{
using std::cout;
Tv s42;
cout << "Inital setting for 42\" TV:\n";
s42.settings();
s42.onoff();
s42.chanup();
cout << "\nAdjusted settings for 42\" TV:\n";
s42.chanup();
cout << "\nAdjusted setting for 42\" TV:\n";
s42.settings(); Remote grey;
grey.set_chan(s42, );
grey.volup(s42);
grey.volup(s42);
cout << "\n42\" settings after using remote:\n";
grey.showmode();
s42.changemode(grey);
grey.showmode();
s42.settings(); Tv s58(Tv::On);
s58.set_mode();
grey.set_chan(s58, );
cout << "\n58\" settings:\n";
s58.settings(); return ;
}

15.8.2

#include <iostream>
#include <exception>
#include <stdexcept> class bad_hmean : public std::logic_error
{
public:
bad_hmean() : logic_error("hmean(), invalid_arguments: a = -b") {}
}; class bad_gmean : public std::logic_error
{
public:
bad_gmean() : logic_error("gmean() arguments should be >= 0") {}
};
#include <iostream>
#include <cmath>
#include "15.8.2.h" double hmean(double a, double b)
{
if(a == -b)
{
throw bad_hmean();
}
}
double gmean(double a, double b)
{
if(a < || b < )
{
throw bad_gmean();
}
return std::sqrt(a * b);
} int main()
{
using std::cout;
using std::cin;
using std::endl; double x, y, z; cout << "Enter two numbers: ";
while(cin >> x >> y)
{
try
{
z = hmean(x, y);
cout << "Harmonic mean of " << x << " and " << y << " is " << z << endl;
cout << "Gepmetric mean of " << x << " and " << y << " is " << gmean(x, y) << endl;
cout << "Enter next set of numbers <q to quit>: ";
}
catch(bad_hmean & bg)
{
cout << bg.what() << endl;
cout << "Try again.\n";
continue;
}
catch(bad_gmean & hg)
{
cout << hg.what() << endl;
cout << "Sorry, you don't get to play any more.\n";
break;
}
}
cout << "Bye!\n"; return ;
}

15.8.3

#include <iostream>
#include <exception>
#include <stdexcept> class bad_mean : public std::logic_error
{
public:
bad_mean(int a, int b, const char * mesg) : __a(a), __b(b), logic_error(mesg) {}
virtual int GetA() {return __a;}
virtual int GetB() {return __b;}
virtual void report() {}
private:
int __a, __b;
}; class bad_hmean : public bad_mean
{
public:
bad_hmean(int a, int b) : bad_mean(a, b, "invalid_arguments: a = -b") {}
virtual void report()
{
std::cout << "hmean(" << GetA() << ", " << GetB() << ")" << what() << std::endl;
}
}; class bad_gmean : public bad_mean
{
public:
bad_gmean(int a, int b) : bad_mean(a, b, "arguments should be >= 0") {}
virtual void report()
{
std::cout << "gmean(" << GetA() << ", " << GetB() << ")" << what() << std::endl;
}
};
#include <iostream>
#include <cmath>
#include "15.8.3.h" double hmean(double a, double b)
{
if(a == -b)
{
throw bad_hmean(a, b);
}
}
double gmean(double a, double b)
{
if(a < || b < )
{
throw bad_gmean(a, b);
}
return std::sqrt(a * b);
} int main()
{
using std::cout;
using std::cin;
using std::endl; double x, y, z; cout << "Enter two numbers: ";
while(cin >> x >> y)
{
try
{
z = hmean(x, y);
cout << "Harmonic mean of " << x << " and " << y << " is " << z << endl;
cout << "Gepmetric mean of " << x << " and " << y << " is " << gmean(x, y) << endl;
cout << "Enter next set of numbers <q to quit>: ";
}
catch(bad_mean & hg)
{
hg.report();
//cout << "Sorry, you don't get to play any more.\n";
break;
}
}
cout << "Bye!\n"; return ;
}

15.8.4

#include <stdexcept>
#include <string> class Sales
{
public:
enum {MONTHS = }; // could be a static const
class bad_index : public std::logic_error
{
private:
int bi; // bad index value
public:
explicit bad_index(int ix, const std::string & s = "Index error in Sales object\n");
virtual ~bad_index() throw() {}
int bi_val() const {return bi;}
}; explicit Sales(int yy = );
Sales(int yy, const double * gr, int n);
virtual ~Sales() {} int Year() const {return year;}
virtual double operator[](int i) const;
virtual double & operator[](int i); private:
double gross[MONTHS];
int year;
}; class LabeledSales : public Sales
{
public:
class nbad_index : public Sales::bad_index
{
private:
std::string lbl;
public:
nbad_index(const std::string & lb, int ix, const std::string & s = "Index error in LabeledSales object\n");
const std::string & label_val() const {return lbl;}
virtual ~nbad_index() throw() {}
}; explicit LabeledSales(const std::string & lb = "none", int yy = );
LabeledSales(const std::string & lb, int yy, const double * gr, int n);
virtual ~LabeledSales() {} const std::string & Label() const {return label;}
virtual double operator[](int i) const;
virtual double & operator[](int i); private:
std::string label;
};
#include "15.8.4.h"
using std::string; Sales::bad_index::bad_index(int ix, const string & s) : std::logic_error(s), bi(ix)
{ } Sales::Sales(int yy)
{
year = yy;
for(int i = ; i < MONTHS; i++)
{
gross[i] = ;
}
} Sales::Sales(int yy, const double * gr, int n)
{
year = yy;
int lim = (n < MONTHS) ? n : MONTHS;
int i;
for(i = ; i < lim; i++)
{
gross[i] = gr[i];
}
for(; i < MONTHS; i++)
{
gross[i] = ;
}
} double Sales::operator[](int i) const
{
if(i < || i >= MONTHS)
{
throw bad_index(i);
}
return gross[i];
} double & Sales::operator[](int i)
{
if(i < || i >= MONTHS)
{
throw bad_index(i);
}
return gross[i];
} LabeledSales::nbad_index::nbad_index(const string & lb, int ix, const string & s) : Sales::bad_index(ix, s)
{
lbl = lb;
} LabeledSales::LabeledSales(const string & lb, int yy) : Sales(yy)
{
label = lb;
} LabeledSales::LabeledSales(const string & lb, int yy, const double * gr, int n) : Sales(yy, gr, n)
{
label = lb;
} double LabeledSales::operator[](int i) const
{
if(i < || i >= MONTHS)
{
throw nbad_index(Label(), i);
}
return Sales::operator[](i);
} double & LabeledSales::operator[](int i)
{
if(i < || i >= MONTHS)
{
throw nbad_index(Label(), i);
}
return Sales::operator[](i);
}
#include <iostream>
#include <typeinfo>
#include "15.8.4.h"
using namespace std; int main()
{
double vals1[] = {, , , , , ,
, , , , , };
double vals2[] = {, , , , , ,
, , , , , };
Sales sales1(, vals1, );
LabeledSales sales2("Blogstar", , vals2, ); cout << "First try block:\n";
try
{
cout << "Year = " << sales1.Year() << endl;
for(int i = ; i < ; i++)
{
cout << sales1[i] << ' ';
if(i % == )
{
cout << endl;
}
}
cout << "Year = " << sales2.Year() << endl;
cout << "Label = " << sales2.Label() << endl; for(int i = ; i <= ; i++)
{
cout << sales2[i] << ' ';
if(i % == )
{
cout << endl;
}
}
cout << "End of try block 1.\n";
}
catch(Sales::bad_index & bad)
{
cout << bad.what();
if(typeid(LabeledSales::nbad_index) == typeid(bad))
{
LabeledSales::nbad_index * nbad = static_cast<LabeledSales::nbad_index *>(&bad);
cout << "Company: " << nbad->label_val() << endl;
}
cout << "bad index: " << bad.bi_val() << endl;
} cout << "\nNext try block:\n";
try
{
sales2[] = 37.5;
sales1[] = ;
cout << "End of try block 2.\n";
}
catch(Sales::bad_index & bad)
{
cout << bad.what();
if(LabeledSales::nbad_index * nbad = dynamic_cast<LabeledSales::nbad_index *>(&bad))
{
cout << "Company: " << nbad->label_val() << endl;
}
cout << "bad index: " << bad.bi_val() << endl;
}
cout << "done\n"; return ;
}

17.8.1

#include <iostream>
using namespace std; int main()
{
long count = ;
while(cin.get() != '$')
{
count++;
}
cin.putback('$');
cout << count << endl;
cout << (char)cin.peek() << endl; return ;
}

17.8.2

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
using namespace std; int main(int argc, char * argvs[])
{
if(argc == )
{
cerr << "No output file" << endl;
exit(EXIT_FAILURE);
} char ch;
ostringstream outstr;
while((ch = cin.get()) != '$')
{
outstr << ch;
}
string s = outstr.str(); ofstream fout(argvs[]);
fout << s;
fout.close(); return ;
}

17.8.3

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std; int main(int argc, char * argv[])
{
if(argc == || argc == || argc >= )
{
cerr << "Error input" << endl;
cerr << "17.8.3 input.txt output.txt" <<endl;
exit(EXIT_FAILURE);
}
ifstream fin(argv[]);
ofstream fout(argv[]);
if(!fin.is_open() || !fout.is_open())
{
cerr << "Error in open file" << endl;
}
char ch;
while(!fin.eof())
{
fin.get(ch);
fout.put(ch);
}
fin.close();
fout.close(); return ;
}

17.8.4

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std; int main(int argc, char * argv[])
{
if(argc <= || argc >= )
{
cerr << "Error input" << endl;
cerr << "17.8.4 input1.txt input2.txt output.txt" <<endl;
exit(EXIT_FAILURE);
}
ifstream fin_1(argv[]), fin_2(argv[]);
ofstream fout(argv[]);
if(!fin_1.is_open() || !fin_2.is_open() || !fout.is_open())
{
cerr << "Error in open file" << endl;
}
string s;
while(!fin_1.eof() && !fin_2.eof())
{
getline(fin_1, s);
fout << s << " ";
getline(fin_2, s);
fout << s << endl;
}
while(!fin_1.eof())
{
getline(fin_1, s);
fout << s << endl;
}
while(!fin_2.eof())
{
getline(fin_2, s);
fout << s << endl;
}
fin_1.close();
fin_2.close();
fout.close(); return ;
}

17.8.5

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <set>
using namespace std; int main()
{
ifstream fin_1("mat.dat"), fin_2("pat.dat");
ofstream fout("matnpat.dat");
if(!fin_1.is_open() || !fin_2.is_open() || !fout.is_open())
{
cerr << "Error" << endl;
exit(EXIT_FAILURE);
} string s;
set<string> myset;
set<string>::iterator it;
while(!fin_1.eof())
{
getline(fin_1, s);
myset.insert(s);
}
while(!fin_2.eof())
{
getline(fin_2, s);
myset.insert(s);
}
for(it = myset.begin(); it != myset.end(); it++)
{
fout << *it << endl;
}
fin_1.close();
fin_2.close();
fout.close(); return ;
}

17.8.7

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
using namespace std; void ShowStr(const string & s)
{
cout << s << endl;
} class Store
{
public:
Store(ofstream & fout_) : fout(fout_) {}
void operator()(const string & s)
{
len = s.length();
fout.write((char *)&len, sizeof(size_t));
fout.write((char *)s.c_str(), len);
}
private:
ofstream & fout;
size_t len;
}; void GetStrs(ifstream & fin, vector<string> & vistr)
{
while(!fin.eof())
{
size_t len = ;
fin.read((char *)&len, sizeof(size_t));
char ch;
string s;
for(size_t i = ; i < len; i++)
{
fin.read((char *)&ch, sizeof(char));
s.push_back(ch);
}
vistr.push_back(s);
}
} int main()
{
vector<string> vostr;
string temp; //acquire strings
cout << "Enter strings (empty line to quit): \n";
while(getline(cin, temp) && temp[] != '\0')
{
vostr.push_back(temp);
}
cout << "Here is your input. \n";
for_each(vostr.begin(), vostr.end(), ShowStr); //store in a file
ofstream fout("strings.dat", ios_base::out | ios_base::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));
fout.close(); //recover file contents
vector<string> vistr;
ifstream fin("strings.dat", ios_base::in | ios_base::binary);
if(!fin.is_open())
{
cerr << "Could not open file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read from the file: \n";
for_each(vistr.begin(), vistr.end(), ShowStr); return ;
}

C++ Primer Plus(第6版)中文版——课后练习程序代码的更多相关文章

  1. 推荐《C Primer Plus(第五版)中文版》【worldsing笔记】

      老外写的C书,看了你会有一种哇塞的感觉,这里提供PDF扫描版的下在,包含数内的例程,请大家支持原版!! C Primer Plus(第五版)中文版.pdf  下载地址:http://pan.bai ...

  2. 《C Primer Plus(第6版)(中文版)》普拉达(作者)epub+mobi+azw3

    内容简介 <C Primer Plus(第6版)中文版>详细讲解了C语言的基本概念和编程技巧. <C Primer Plus(第6版)中文版>共17章.第1.2章介绍了C语言编 ...

  3. c++ primer plus 第6版 部分一 1-4章

    c++ primer plus 第6版 源代码 ---编译器---目标代码---连接程序(启动代码--库代码)---可执行代码 源代码扩展名:c   cc   cxx     C    cpp     ...

  4. C++ Primer Plus 第六版笔记

    C++ Primer Plus 第六版笔记 关于对象声明的思考 转自:http://www.cnblogs.com/weiqubo/archive/2009/11/02/1930042.html C+ ...

  5. 《JavaScript权威指南 第六版 中文版》(一)

    <JavaScript权威指南 第六版 中文版> 第二章 词法结构 2.1字符集 JavaScript是使用Unicode字符集编码写的. 2.1.1区分大小写 JavaScript是区分 ...

  6. C Primer Plus(第五版)1

    这是C Primer Plus(第五版)的第一章,上传上来主要是方便我进行做笔记,写注释,还有我会删掉一些“废话”等. 1.1 C语言的起源 贝尔实验室的 Dennis Ritchie 在1972年开 ...

  7. 【原创】一起学C++ 之指针、数组、指针算术 ---------C++ primer plus(第6版)

    C++ Primer Plus 第6版 指针和数组基本等价的原因在于指针算术! 一.指针 ⑴整数变量+1后,其值将增加1: ⑵指针变量+1后,增加的量等于它指向的类型的字节数: ⑶C++将数组名解析为 ...

  8. 【原创】一起学C++ 之 字符串 ---------C++ primer plus(第6版)

    C++ Primer Plus 第6版 字符串:是存储在内存的连续字节中的一系列字符. C++处理字符串的方式有2种: 一.来自C语言.常被称为C-风格字符串(C-Style-string) 1)从字 ...

  9. JavaScript权威指南(第6版)(中文版)笔记

      JavaScript权威指南(第6版)(中文版)笔记      

随机推荐

  1. Ubuntu上glibc CVE-2015-7547漏洞的POC验证和修复

    Ubuntu上查看Glibc版本 $ldd --version ldd (Ubuntu GLIBC 2.21-0ubuntu4) 2.21 Ubuntu上查看使用Glibc的相关程序 sudo lso ...

  2. CSS before和after伪元素

    CSS中有一个特性允许我们添加额外元素而不扰乱文档本身,它们是以CSS选择器的形式出现的,具有标签的表现效果,但是呢又不是真正的标签元素,所以叫做“伪元素”.下面就说一下常见的两个伪元素before和 ...

  3. Sublime Text 2 自动开启换行 Word Wrap

    首先当然要夸一下神器 Sublime Text 2,自从第一次用我就彻底把神马 Notepad++ 和 TextMate 打入冷宫,用来开发 WEB 项目从此 IDE 都不需要了! 下面讲讲如何自动开 ...

  4. iOS几种简单有效的数组排序方法

    第一种,利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象 NSComparator cmptr = ^(id obj1 ...

  5. Android Studio使用教程图文详解

    谷歌表示Android Studio 1.0 能让开发者“更快更有生产力”,并认为它可以代替 Eclipse,同时为Eclipse 用户提供迁移步骤.代码自动提示.运行响应速度.都比Eclipse来的 ...

  6. 重新开始学习javase_隐藏实施过程

    一.隐藏实施过程 对于隐藏实施过程,thinking in java中讲了很好,无非就是一个好的程序尽量做到,对外公开的程序,即使内部程序发生变动,也不会影响这些公开的服务的使用 类的导入java中的 ...

  7. Direct2D 加载位图

    说明: 通过WIC从文件加载位图. 可缩放后加载到内存. 源码: HRESULT LoadImageFormFile( IWICImagingFactory *pWicFactory, ID2D1Re ...

  8. cocos2d-x 音乐播放猜想

    "SimpleAudioEngine.cpp": void SimpleAudioEngine::playBackgroundMusic(const char* pszFilePa ...

  9. UVA 10254 - The Priest Mathematician (dp | 汉诺塔 | 找规律 | 大数)

    本文出自   http://blog.csdn.net/shuangde800 题目点击打开链接 题意: 汉诺塔游戏请看 百度百科 正常的汉诺塔游戏是只有3个柱子,并且如果有n个圆盘,至少需要2^n- ...

  10. 将CSS CLIP属性应用在:扩展覆盖效果

    我们想要展示如何利用CSS3 clip属性制作一种简单而整洁的扩展效果,当点击一个box元素时实现平稳过渡.这个想法是为了实现某种叠加效果,好像它实际上在各个元素的下面.点击其中一个元素将创建一个切断 ...