浏览代码

C++ Primer Plus V6 源码

蘭雅sRGB 23 小时之前
父节点
当前提交
e07659193e
共有 100 个文件被更改,包括 4996 次插入0 次删除
  1. 9 0
      CPPlusV6/Appendix E/align.cpp
  2. 78 0
      CPPlusV6/Appendix E/memb_pt.cpp
  3. 40 0
      CPPlusV6/Appendix E/noex.cpp
  4. 23 0
      CPPlusV6/Appendix G/appg01.cpp
  5. 29 0
      CPPlusV6/Appendix G/appg02.cpp
  6. 57 0
      CPPlusV6/Appendix G/appg04.cpp
  7. 27 0
      CPPlusV6/Appendix G/appg3.cpp
  8. 26 0
      CPPlusV6/Appendix G/perfectf.cpp
  9. 38 0
      CPPlusV6/Chapter 10/stack.cpp
  10. 22 0
      CPPlusV6/Chapter 10/stack.h
  11. 46 0
      CPPlusV6/Chapter 10/stacker.cpp
  12. 69 0
      CPPlusV6/Chapter 10/stock00.cpp
  13. 24 0
      CPPlusV6/Chapter 10/stock00.h
  14. 80 0
      CPPlusV6/Chapter 10/stock01.cpp
  15. 99 0
      CPPlusV6/Chapter 10/stock10.cpp
  16. 23 0
      CPPlusV6/Chapter 10/stock10.h
  17. 103 0
      CPPlusV6/Chapter 10/stock20.cpp
  18. 25 0
      CPPlusV6/Chapter 10/stock20.h
  19. 16 0
      CPPlusV6/Chapter 10/stocks.cpp
  20. 110 0
      CPPlusV6/Chapter 10/temp20.cpp
  21. 21 0
      CPPlusV6/Chapter 10/usestok0.cpp
  22. 30 0
      CPPlusV6/Chapter 10/usestok1.cpp
  23. 30 0
      CPPlusV6/Chapter 10/usestok2.cpp
  24. 46 0
      CPPlusV6/Chapter 11/mytime.cpp
  25. 19 0
      CPPlusV6/Chapter 11/mytime0.h
  26. 46 0
      CPPlusV6/Chapter 11/mytime1.cpp
  27. 19 0
      CPPlusV6/Chapter 11/mytime1.h
  28. 65 0
      CPPlusV6/Chapter 11/mytime2.cpp
  29. 21 0
      CPPlusV6/Chapter 11/mytime2.h
  30. 66 0
      CPPlusV6/Chapter 11/mytime3.cpp
  31. 25 0
      CPPlusV6/Chapter 11/mytime3.h
  32. 51 0
      CPPlusV6/Chapter 11/randwalk.cpp
  33. 40 0
      CPPlusV6/Chapter 11/stone.cpp
  34. 17 0
      CPPlusV6/Chapter 11/stone1.cpp
  35. 41 0
      CPPlusV6/Chapter 11/stonewt.cpp
  36. 19 0
      CPPlusV6/Chapter 11/stonewt.h
  37. 54 0
      CPPlusV6/Chapter 11/stonewt1.cpp
  38. 22 0
      CPPlusV6/Chapter 11/stonewt1.h
  39. 33 0
      CPPlusV6/Chapter 11/usetime0.cpp
  40. 44 0
      CPPlusV6/Chapter 11/usetime1.cpp
  41. 40 0
      CPPlusV6/Chapter 11/usetime2.cpp
  42. 23 0
      CPPlusV6/Chapter 11/usetime3.cpp
  43. 170 0
      CPPlusV6/Chapter 11/vect.cpp
  44. 45 0
      CPPlusV6/Chapter 11/vect.h
  45. 99 0
      CPPlusV6/Chapter 12/bank.cpp
  46. 51 0
      CPPlusV6/Chapter 12/placenew1.cpp
  47. 56 0
      CPPlusV6/Chapter 12/placenew2.cpp
  48. 80 0
      CPPlusV6/Chapter 12/queue.cpp
  49. 43 0
      CPPlusV6/Chapter 12/queue.h
  50. 62 0
      CPPlusV6/Chapter 12/sayings1.cpp
  51. 71 0
      CPPlusV6/Chapter 12/sayings2.cpp
  52. 118 0
      CPPlusV6/Chapter 12/string1.cpp
  53. 37 0
      CPPlusV6/Chapter 12/string1.h
  54. 44 0
      CPPlusV6/Chapter 12/strngbad.cpp
  55. 19 0
      CPPlusV6/Chapter 12/strngbad.h
  56. 49 0
      CPPlusV6/Chapter 12/vegnews.cpp
  57. 122 0
      CPPlusV6/Chapter 13/acctabc.cpp
  58. 64 0
      CPPlusV6/Chapter 13/acctabc.h
  59. 133 0
      CPPlusV6/Chapter 13/brass.cpp
  60. 42 0
      CPPlusV6/Chapter 13/brass.h
  61. 109 0
      CPPlusV6/Chapter 13/dma.cpp
  62. 55 0
      CPPlusV6/Chapter 13/dma.h
  63. 12 0
      CPPlusV6/Chapter 13/tabtenn0.cpp
  64. 20 0
      CPPlusV6/Chapter 13/tabtenn0.h
  65. 24 0
      CPPlusV6/Chapter 13/tabtenn1.cpp
  66. 34 0
      CPPlusV6/Chapter 13/tabtenn1.h
  67. 28 0
      CPPlusV6/Chapter 13/usebrass1.cpp
  68. 67 0
      CPPlusV6/Chapter 13/usebrass2.cpp
  69. 62 0
      CPPlusV6/Chapter 13/usebrass3.cpp
  70. 28 0
      CPPlusV6/Chapter 13/usedma.cpp
  71. 22 0
      CPPlusV6/Chapter 13/usett0.cpp
  72. 31 0
      CPPlusV6/Chapter 13/usett1.cpp
  73. 51 0
      CPPlusV6/Chapter 14/arraytp.h
  74. 60 0
      CPPlusV6/Chapter 14/frnd2tmp.cpp
  75. 32 0
      CPPlusV6/Chapter 14/manyfrnd.cpp
  76. 55 0
      CPPlusV6/Chapter 14/pairs.cpp
  77. 51 0
      CPPlusV6/Chapter 14/stacktem.cpp
  78. 61 0
      CPPlusV6/Chapter 14/stacktp.h
  79. 47 0
      CPPlusV6/Chapter 14/stckoptr1.cpp
  80. 78 0
      CPPlusV6/Chapter 14/stcktp1.h
  81. 75 0
      CPPlusV6/Chapter 14/studentc.cpp
  82. 43 0
      CPPlusV6/Chapter 14/studentc.h
  83. 74 0
      CPPlusV6/Chapter 14/studenti.cpp
  84. 41 0
      CPPlusV6/Chapter 14/studenti.h
  85. 42 0
      CPPlusV6/Chapter 14/tempmemb.cpp
  86. 40 0
      CPPlusV6/Chapter 14/tempparm.cpp
  87. 56 0
      CPPlusV6/Chapter 14/tmp2tmp.cpp
  88. 40 0
      CPPlusV6/Chapter 14/twod.cpp
  89. 46 0
      CPPlusV6/Chapter 14/use_stuc.cpp
  90. 45 0
      CPPlusV6/Chapter 14/use_stui.cpp
  91. 74 0
      CPPlusV6/Chapter 14/worker0.cpp
  92. 54 0
      CPPlusV6/Chapter 14/worker0.h
  93. 123 0
      CPPlusV6/Chapter 14/workermi.cpp
  94. 83 0
      CPPlusV6/Chapter 14/workermi.h
  95. 58 0
      CPPlusV6/Chapter 14/workmi.cpp
  96. 24 0
      CPPlusV6/Chapter 14/worktest.cpp
  97. 28 0
      CPPlusV6/Chapter 15/constcast.cpp
  98. 30 0
      CPPlusV6/Chapter 15/error1.cpp
  99. 38 0
      CPPlusV6/Chapter 15/error2.cpp
  100. 34 0
      CPPlusV6/Chapter 15/error3.cpp

+ 9 - 0
CPPlusV6/Appendix E/align.cpp

@@ -0,0 +1,9 @@
+#include <iostream>
+using namespace std;
+
+int main()
+{
+	cout << alignof(double) << endl;
+	cin.get();
+	return 0;
+}

+ 78 - 0
CPPlusV6/Appendix E/memb_pt.cpp

@@ -0,0 +1,78 @@
+// memb_pt.cpp -- dereferencing pointers to class members
+#include <iostream>
+using namespace std;
+
+class Example
+{
+private:
+    int feet;
+    int inches;
+public:
+    Example();
+    Example(int ft);
+    ~Example();
+    void show_in() const;
+    void show_ft() const;
+    void use_ptr() const;
+};
+
+Example::Example()
+{
+    feet = 0;
+    inches = 0;
+}
+
+Example::Example(int ft)
+{
+    feet = ft;
+    inches = 12 * feet;
+}
+
+Example::~Example()
+{
+}
+
+void Example::show_in() const
+{
+    cout << inches << " inches\n";
+}
+
+void Example::show_ft() const
+{
+    cout << feet << " feet\n";
+}
+
+void Example::use_ptr() const
+{
+    Example yard(3);
+    int Example::*pt;
+    pt = &Example::inches;
+    cout << "Set pt to &Example::inches:\n";
+    cout << "this->pt: " << this->*pt << endl;
+    cout << "yard.*pt: " << yard.*pt << endl;
+    pt = &Example::feet;
+    cout << "Set pt to &Example::feet:\n";
+    cout << "this->pt: " << this->*pt << endl;
+    cout << "yard.*pt: " << yard.*pt << endl;
+    void (Example::*pf)() const;
+    pf = &Example::show_in;
+    cout << "Set pf to &Example::show_in:\n";
+    cout << "Using (this->*pf)(): ";
+    (this->*pf)();
+    cout << "Using (yard.*pf)(): ";
+    (yard.*pf)();
+}
+
+int main()
+{
+    Example car(15);
+    Example van(20);
+    Example garage; 
+
+    cout << "car.use_ptr() output:\n";
+    car.use_ptr();
+    cout << "\nvan.use_ptr() output:\n";
+    van.use_ptr();
+    cin.get();
+    return 0;
+}

+ 40 - 0
CPPlusV6/Appendix E/noex.cpp

@@ -0,0 +1,40 @@
+#include <iostream>
+#include <string>
+#include <cmath>
+#include <numeric>
+#include <vector>
+#include <algorithm>
+#include <unordered_set>
+using namespace std;
+struct S {double a; double b;};
+int main()
+{
+	S a = {1.1,2.2};
+	S b = {2.1,4.2};
+	S c = {3.1,5.2};
+
+	unordered_set<S*> us;
+	us.insert(&a);
+	us.insert(&b);
+	us.insert(&c);
+	for_each(us.begin(),us.end(),[](S* i) {cout << (*i).a << ", ";});
+	cout << "\nNext\n";
+
+	
+/*	if(pt != vi.end())
+		cout  << *pt << endl;
+	else
+		cout << "not found\n";
+	cout << vi.count("cow") << endl;
+	cout << vi.count("fondu") << endl;
+	cout << endl;
+	cout << *vi.lower_bound("cow") << endl;
+	cout << *vi.upper_bound("hen") << endl;
+	cout << vi.bucket_count() << endl;
+	cout << vi.bucket("cow") << endl;
+	cout << vi.bucket("starkA") << endl;
+	cout << vi.bucket("stark") << endl;*/
+
+	cin.get();
+		
+}

+ 23 - 0
CPPlusV6/Appendix G/appg01.cpp

@@ -0,0 +1,23 @@
+#include <iostream>
+#include <vector>
+#include <string>
+#include <algorithm>
+using namespace std;
+
+int main()
+{
+vector<string> input;
+string temp;
+while (cin >> temp && temp != "quit")
+    input.push_back(temp);
+vector<string>::iterator want=
+    find(input.begin(), input.end(), string("bonus"));
+if (want != input.end())
+{
+    vector<string>::reference r = *want;
+    r = "bogus";
+}
+for_each(input.begin(), input.end(), [](string s){cout << s << ", ";});
+cin.get();
+cin.get();
+}

+ 29 - 0
CPPlusV6/Appendix G/appg02.cpp

@@ -0,0 +1,29 @@
+#include <iostream>
+#include <vector>
+#include <string>
+#include <algorithm>
+using namespace std;
+
+template<typename Bag>
+typename Bag::value_type min(const Bag & b)
+{
+    typename Bag::const_iterator it;
+    typename Bag::value_type m = *b.begin();
+    for (it = b.begin(); it != b.end(); ++it)
+        if (*it < m)
+            m = *it;
+    return m;
+}
+
+int main()
+{
+vector<int> temperatures;
+int temp;
+while (cin >> temp && temp >-274)
+    temperatures.push_back(temp);
+int coldest = min(temperatures);
+for_each(temperatures.begin(), temperatures.end(), [](int s){cout << s << ", ";});
+cout << endl << coldest << endl;
+cin.get();
+cin.get();
+}

+ 57 - 0
CPPlusV6/Appendix G/appg04.cpp

@@ -0,0 +1,57 @@
+// setops.cpp -- some set operations
+#include <iostream>
+#include <string>
+#include <set>
+#include <algorithm>
+#include <iterator>
+
+int main()
+{
+    using namespace std;
+    const int N = 6;
+    string s1[N] = {"buffoon", "thinkers", "for", "heavy", "can", "for"};
+    string s2[N] = {"metal", "any", "food", "elegant", "deliver","for"};
+
+    set<string> A(s1, s1 + N);
+    set<string> B(s2, s2 + N);
+	A.insert("buffalo");
+    ostream_iterator<string, char> out(cout, " ");
+    cout << "Set A: ";
+    copy(A.begin(), A.end(), out);
+    cout << endl;
+    cout << "Set B: ";
+    copy(B.begin(), B.end(), out);
+    cout << endl;
+
+    cout << "Union of A and B:\n";
+    set_union(A.begin(), A.end(), B.begin(), B.end(), out);
+    cout << endl;
+
+    cout << "Intersection of A and B:\n";
+    set_intersection(A.begin(), A.end(), B.begin(), B.end(), out);
+    cout << endl;
+
+    cout << "Difference of A and B:\n";
+    set_difference(A.begin(), A.end(), B.begin(), B.end(), out);
+    cout << endl;
+
+    set<string> C;
+    cout << "Set C:\n";
+    set_union(A.begin(), A.end(), B.begin(), B.end(),
+        insert_iterator<set<string> >(C, C.begin()));
+    copy(C.begin(), C.end(), out);
+    cout << endl;
+
+    string s3("grungy");
+    C.insert(s3);
+    cout << "Set C after insertion:\n";
+    copy(C.begin(), C.end(),out);
+    cout << endl;
+
+    cout << "Showing a range:\n";
+    copy(C.lower_bound("ghost"),C.upper_bound("spook"), out);
+    cout << endl;
+	cin.get();
+	cin.get();
+    return 0; 
+}

+ 27 - 0
CPPlusV6/Appendix G/appg3.cpp

@@ -0,0 +1,27 @@
+#include <iostream>
+#include <vector>
+#include <algorithm>
+using namespace std;
+
+class Items
+{
+    double x;
+    double y;
+    int m;
+public:
+	Items() : x(0),y(0), m(0){};      // #1
+    Items (double xx, double yy, int mm): x(xx),y(yy), m(mm){}; // #2
+	void Show() const { cout << x << ", " << y << ", " << m << endl;}
+};
+int main()
+{
+	vector<Items> vt(5);
+
+	for_each( vt.begin(), vt.end(), [](const Items & i){i.Show();});
+
+    vt.push_back( Items(8.2, 2.8, 3));  //
+	for_each( vt.begin(), vt.end(), [](const Items & i){i.Show();});
+	vt.emplace_back( 8.2, 2.8, 3);  //
+	for_each( vt.begin(), vt.end(), [](const Items & i){i.Show();});
+	cin.get();
+}

+ 26 - 0
CPPlusV6/Appendix G/perfectf.cpp

@@ -0,0 +1,26 @@
+#include <iostream>
+#include <vector>
+#include <algorithm>
+using namespace std;
+
+class Items
+{
+    double x;
+    double y;
+    int m;
+public:
+	Items() : x(0),y(0), m(0){};      // #1
+    Items (double xx, double yy, int mm): x(xx),y(yy), m(mm){}; // #2
+	void Show() const { cout << x << ", " << y << ", " << m << endl;}
+};
+
+template<typename...Args>
+  void dumb(int i, Args... args)
+  {
+	  cout << i << endl;
+	  Items(args...).Show();
+  }
+int main()
+{
+	dumb(10, 2.2,4.4,1);
+}

+ 38 - 0
CPPlusV6/Chapter 10/stack.cpp

@@ -0,0 +1,38 @@
+// stack.cpp -- Stack member functions
+#include "stack.h"
+Stack::Stack()    // create an empty stack
+{
+    top = 0;
+}
+
+bool Stack::isempty() const
+{
+    return top == 0;
+}
+
+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 > 0)
+    {
+        item = items[--top];
+        return true;
+    }
+    else
+        return false; 
+}

+ 22 - 0
CPPlusV6/Chapter 10/stack.h

@@ -0,0 +1,22 @@
+// stack.h -- class definition for the stack ADT
+#ifndef STACK_H_
+#define STACK_H_
+
+typedef unsigned long Item;
+
+class Stack
+{
+private:
+    enum {MAX = 10};    // 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;
+    // 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
+};
+#endif

+ 46 - 0
CPPlusV6/Chapter 10/stacker.cpp

@@ -0,0 +1,46 @@
+// stacker.cpp -- testing the Stack class
+#include <iostream>
+#include <cctype>  // or ctype.h
+#include "stack.h"
+int main()
+{
+    using namespace std;
+    Stack st; // create an empty stack
+    char ch;
+    unsigned long po;
+    cout << "Please enter A to add a purchase order,\n"
+        << "P to process a PO, or Q to quit.\n";
+    while (cin >> ch && toupper(ch) != 'Q')
+    {
+        while (cin.get() != '\n')   
+            continue;
+        if (!isalpha(ch))
+        {
+            cout << '\a';
+            continue;
+        }
+        switch(ch)
+        {
+             case 'A':
+             case 'a': cout << "Enter a PO number to add: ";
+                       cin >> po;
+                       if (st.isfull())
+                           cout << "stack already full\n";
+                       else
+                           st.push(po);
+                       break;
+             case 'P':
+             case 'p': if (st.isempty())
+                           cout << "stack already empty\n";
+                       else {
+                           st.pop(po);
+                           cout << "PO #" << po << " popped\n";
+                       }
+                       break;
+        }
+        cout << "Please enter A to add a purchase order,\n"
+             << "P to process a PO, or Q to quit.\n";
+    }
+    cout << "Bye\n";
+    return 0; 
+}

+ 69 - 0
CPPlusV6/Chapter 10/stock00.cpp

@@ -0,0 +1,69 @@
+// stock00.cpp -- implementing the Stock class
+// version 00
+#include <iostream>
+#include "stock00.h"
+
+void Stock::acquire(const std::string & co, long n, double pr)
+{
+    company = co;
+    if (n < 0)
+    {
+        std::cout << "Number of shares can't be negative; "
+                  << company << " shares set to 0.\n";
+        shares = 0;
+    }
+    else
+        shares = n;
+    share_val = pr;
+    set_tot();
+}
+
+void Stock::buy(long num, double price)
+{
+     if (num < 0)
+    {
+        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)
+{
+    using std::cout;
+    if (num < 0)
+    {
+        cout << "Number of shares sold can't be negative. "
+             << "Transaction is aborted.\n";
+    }
+    else if (num > shares)
+    {
+        cout << "You can't 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();
+}
+
+void Stock::show()
+{
+    std::cout << "Company: " << company
+              << "  Shares: " << shares << '\n'
+              << "  Share Price: $" << share_val
+              << "  Total Worth: $" << total_val << '\n';
+}

+ 24 - 0
CPPlusV6/Chapter 10/stock00.h

@@ -0,0 +1,24 @@
+// stock00.h -- Stock class interface
+// version 00
+#ifndef STOCK00_H_
+#define STOCK00_H_
+
+#include <string>  
+
+class Stock  // class declaration
+{
+private: 
+    std::string company;
+    long shares;
+    double share_val;
+    double total_val;
+    void set_tot() { total_val = shares * share_val; }
+public:
+    void acquire(const std::string & co, long n, double pr);
+    void buy(long num, double price);
+    void sell(long num, double price);
+    void update(double price);
+    void show();
+};    // note semicolon at the end
+
+#endif

+ 80 - 0
CPPlusV6/Chapter 10/stock01.cpp

@@ -0,0 +1,80 @@
+// stock01.cpp -- revised show() method
+#include <iostream>
+#include "stock00.h"
+
+void Stock::acquire(const std::string & co, long n, double pr)
+{
+    company = co;
+    if (n < 0)
+    {
+        std::cerr << "Number of shares can't be negative; "
+                  << company << " shares set to 0.\n";
+        shares = 0;
+    }
+    else
+        shares = n;
+    share_val = pr;
+    set_tot();
+}
+
+void Stock::buy(long num, double price)
+{
+     if (num < 0)
+    {
+        std::cerr << "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)
+{
+    using std::cerr;
+    if (num < 0)
+    {
+        cerr << "Number of shares sold can't be negative. "
+             << "Transaction is aborted.\n";
+    }
+    else if (num > shares)
+    {
+        cerr << "You can't 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();
+}
+
+void Stock::show()
+{
+    using std::cout;
+    using std::ios_base;
+    // set format to #.###
+    ios_base::fmtflags orig = cout.setf(ios_base::fixed); 
+    int prec = cout.precision(3);
+
+    cout << "Company: " << company
+        << "  Shares: " << shares << '\n';
+    cout << "  Share Price: $" << share_val;
+    // set format to *.**
+    cout.precision(2);
+    cout << "  Total Worth: $" << total_val << '\n';
+
+    // restore original format
+    cout.setf(orig, ios_base::floatfield);
+    cout.precision(prec);
+}

+ 99 - 0
CPPlusV6/Chapter 10/stock10.cpp

@@ -0,0 +1,99 @@
+// stock1.cpp – Stock class implementation with constructors, destructor added
+#include <iostream>
+#include "stock10.h"
+
+// constructors (verbose versions)
+Stock::Stock()        // default constructor
+{
+    std::cout << "Default constructor called\n";
+    company = "no name";
+    shares = 0;
+    share_val = 0.0;
+    total_val = 0.0;
+}
+
+Stock::Stock(const std::string & co, long n, double pr)
+{
+    std::cout << "Constructor using " << co << " called\n";
+    company = co;
+
+    if (n < 0)
+    {
+        std::cout << "Number of shares can't be negative; "
+                   << company << " shares set to 0.\n";
+        shares = 0;
+    }
+    else
+        shares = n;
+    share_val = pr;
+    set_tot();
+}
+// class destructor
+Stock::~Stock()        // verbose class destructor
+{
+    std::cout << "Bye, " << company << "!\n";
+}
+
+// other methods
+void Stock::buy(long num, double price)
+{
+     if (num < 0)
+    {
+        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)
+{
+    using std::cout;
+    if (num < 0)
+    {
+        cout << "Number of shares sold can't be negative. "
+             << "Transaction is aborted.\n";
+    }
+    else if (num > shares)
+    {
+        cout << "You can't 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();
+}
+
+void Stock::show()
+{
+    using std::cout;
+    using std::ios_base;
+    // set format to #.###
+    ios_base::fmtflags orig = 
+        cout.setf(ios_base::fixed, ios_base::floatfield); 
+    std::streamsize prec = cout.precision(3);
+
+    cout << "Company: " << company
+        << "  Shares: " << shares << '\n';
+    cout << "  Share Price: $" << share_val;
+    // set format to #.##
+    cout.precision(2);
+    cout << "  Total Worth: $" << total_val << '\n';
+
+    // restore original format
+    cout.setf(orig, ios_base::floatfield);
+    cout.precision(prec);
+}

+ 23 - 0
CPPlusV6/Chapter 10/stock10.h

@@ -0,0 +1,23 @@
+// stock10.h – Stock class declaration with constructors, destructor added
+#ifndef STOCK1_H_
+#define STOCK1_H_
+#include <string>
+class Stock
+{
+private:
+    std::string company;
+    long shares;
+    double share_val;
+    double total_val;
+    void set_tot() { total_val = shares * share_val; }
+public:
+    Stock();        // default constructor
+    Stock(const std::string & co, long n = 0, double pr = 0.0);
+    ~Stock();       // noisy destructor
+    void buy(long num, double price);
+    void sell(long num, double price);
+    void update(double price);
+    void show();
+};
+
+#endif

+ 103 - 0
CPPlusV6/Chapter 10/stock20.cpp

@@ -0,0 +1,103 @@
+// stock20.cpp -- augmented version
+#include <iostream>
+#include "stock20.h"
+using namespace std;
+// constructors
+Stock::Stock()        // default constructor
+{
+    shares = 0;
+    share_val = 0.0;
+    total_val = 0.0;
+}
+
+Stock::Stock(const std::string & co, long n, double pr)
+{
+    company = co;
+    if (n < 0)
+    {
+        std::cout << "Number of shares can't be negative; "
+                   << company << " shares set to 0.\n";
+        shares = 0;
+    }
+    else
+        shares = n;
+    share_val = pr;
+    set_tot();
+}
+
+// class destructor
+Stock::~Stock()        // quiet class destructor
+{
+}
+
+// other methods
+void Stock::buy(long num, double price)
+{
+     if (num < 0)
+    {
+        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)
+{
+    using std::cout;
+    if (num < 0)
+    {
+        cout << "Number of shares sold can't be negative. "
+             << "Transaction is aborted.\n";
+    }
+    else if (num > shares)
+    {
+        cout << "You can't 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();
+}
+
+void Stock::show() const
+{
+    using std::cout;
+    using std::ios_base;
+    // set format to #.###
+    ios_base::fmtflags orig = 
+        cout.setf(ios_base::fixed, ios_base::floatfield); 
+    std::streamsize prec = cout.precision(3);
+
+    cout << "Company: " << company
+        << "  Shares: " << shares << '\n';
+    cout << "  Share Price: $" << share_val;
+    // set format to #.##
+    cout.precision(2);
+    cout << "  Total Worth: $" << total_val << '\n';
+
+    // restore original format
+    cout.setf(orig, ios_base::floatfield);
+    cout.precision(prec);
+}
+
+const Stock & Stock::topval(const Stock & s) const
+{
+    if (s.total_val > total_val)
+        return s;
+    else
+        return *this; 
+}

+ 25 - 0
CPPlusV6/Chapter 10/stock20.h

@@ -0,0 +1,25 @@
+// stock20.h -- augmented version
+#ifndef STOCK20_H_
+#define STOCK20_H_
+#include <string>
+
+class Stock
+{
+private:
+    std::string company;
+    int shares;
+    double share_val;
+    double total_val;
+    void set_tot() { total_val = shares * share_val; }
+public:
+  //  Stock();        // default constructor
+    Stock(const std::string & co, long n = 0, double pr = 0.0);
+    ~Stock();       // do-nothing destructor
+    void buy(long num, double price);
+    void sell(long num, double price);
+    void update(double price);
+    void show()const;
+    const Stock & topval(const Stock & s) const;
+};
+
+#endif

+ 16 - 0
CPPlusV6/Chapter 10/stocks.cpp

@@ -0,0 +1,16 @@
+// stocks.cpp -- the whole program
+#include <iostream>
+#include "stocks00.h"
+
+int main()
+{
+    Stock stock1;
+    stock1.acquire("NanoSmart", 20, 12.50);
+    stock1.show();
+    stock1.buy(15, 18.25);
+    stock1.show();
+    stock1.sell(400, 20.00);
+    stock1.show();
+    std::cin.get();
+    return 0;
+}

+ 110 - 0
CPPlusV6/Chapter 10/temp20.cpp

@@ -0,0 +1,110 @@
+// stock20.cpp -- augmented version
+#include <iostream>
+#include "stock20.h"
+using namespace std;
+// constructors
+/*
+Stock::Stock()        // default constructor
+{
+	    std::cout << "Default constructor called\n";
+    company = "no name";
+
+    shares = 0;
+    share_val = 0.0;
+    total_val = 0.0;
+}
+*/
+Stock::Stock(const std::string & co, long n, double pr)
+{
+	   std::cout << "Constructor using " << co << " called\n";
+
+    company = co;
+    if (n < 0)
+    {
+        std::cout << "Number of shares can't be negative; "
+                   << company << " shares set to 0.\n";
+        shares = 0;
+    }
+    else
+        shares = n;
+    share_val = pr;
+    set_tot();
+}
+
+// class destructor
+Stock::~Stock()        // quiet class destructor
+{
+	   std::cout << "Bye, " << company << "!\n";
+}
+
+// other methods
+void Stock::buy(long num, double price)
+{
+     if (num < 0)
+    {
+        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)
+{
+    using std::cout;
+    if (num < 0)
+    {
+        cout << "Number of shares sold can't be negative. "
+             << "Transaction is aborted.\n";
+    }
+    else if (num > shares)
+    {
+        cout << "You can't 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();
+}
+
+void Stock::show() const
+{
+    using std::cout;
+    using std::ios_base;
+    // set format to #.###
+    ios_base::fmtflags orig = 
+        cout.setf(ios_base::fixed, ios_base::floatfield); 
+    std::streamsize prec = cout.precision(3);
+
+    cout << "Company: " << company
+        << "  Shares: " << shares << '\n';
+    cout << "  Share Price: $" << share_val;
+    // set format to #.##
+    cout.precision(2);
+    cout << "  Total Worth: $" << total_val << '\n';
+
+    // restore original format
+    cout.setf(orig, ios_base::floatfield);
+    cout.precision(prec);
+}
+
+const Stock & Stock::topval(const Stock & s) const
+{
+    if (s.total_val > total_val)
+        return s;
+    else
+        return *this; 
+}

+ 21 - 0
CPPlusV6/Chapter 10/usestok0.cpp

@@ -0,0 +1,21 @@
+// usestok0.cpp -- the client program
+// compile with stock.cpp
+#include <iostream>
+#include "stock00.h"
+
+int main()
+{
+    Stock fluffy_the_cat;
+    fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
+    fluffy_the_cat.show();
+    fluffy_the_cat.buy(15, 18.125);
+    fluffy_the_cat.show();
+    fluffy_the_cat.sell(400, 20.00);
+    fluffy_the_cat.show();
+    fluffy_the_cat.buy(300000,40.125);
+    fluffy_the_cat.show();
+    fluffy_the_cat.sell(300000,0.125);
+    fluffy_the_cat.show();
+    // std::cin.get();
+    return 0;
+}

+ 30 - 0
CPPlusV6/Chapter 10/usestok1.cpp

@@ -0,0 +1,30 @@
+// usestok1.cpp -- using the Stock class
+// compile with stock10.cpp
+#include <iostream>
+#include "stock10.h"
+
+int main()
+{
+  {
+    using std::cout;
+    cout << "Using constructors to create new objects\n";
+    Stock stock1("NanoSmart", 12, 20.0);            // syntax 1
+    stock1.show();
+    Stock stock2 = Stock ("Boffo Objects", 2, 2.0); // syntax 2
+    stock2.show();
+
+    cout << "Assigning stock1 to stock2:\n";
+    stock2 = stock1;
+    cout << "Listing stock1 and stock2:\n";
+    stock1.show();
+    stock2.show();
+
+    cout << "Using a constructor to reset an object\n";
+    stock1 = Stock("Nifty Foods", 10, 50.0);    // temp object
+    cout << "Revised stock1:\n";
+    stock1.show();
+    cout << "Done\n";
+  }
+	// std::cin.get();
+    return 0; 
+}

+ 30 - 0
CPPlusV6/Chapter 10/usestok2.cpp

@@ -0,0 +1,30 @@
+// usestok2.cpp -- using the Stock class
+// compile with stock20.cpp
+#include <iostream>
+#include "stock20.h"
+
+const int STKS = 4;
+int main()
+{{
+// create an array of initialized objects
+    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)
+        };
+
+    std::cout << "Stock holdings:\n";
+    int st;
+    for (st = 0; st < STKS; st++)
+        stocks[st].show();
+// set pointer to first element
+    const Stock * top = &stocks[0];
+    for (st = 1; st < STKS; st++)
+        top = &top->topval(stocks[st]);
+// now top points to the most valuable holding
+    std::cout << "\nMost valuable holding:\n";
+	top->show();}
+    // std::cin.get();
+    return 0; 
+}

+ 46 - 0
CPPlusV6/Chapter 11/mytime.cpp

@@ -0,0 +1,46 @@
+// mytime0.cpp  -- implementing Time methods
+#include <iostream>
+#include "mytime0.h"
+
+Time::Time()
+{
+    hours = minutes = 0;
+}
+
+Time::Time(int h, int m )
+{
+    hours = h;
+    minutes = m;
+}
+
+void Time::AddMin(int m)
+{
+    minutes += m;
+    hours += minutes / 60;
+    minutes %= 60;
+}
+
+void Time::AddHr(int h)
+{
+    hours += h;
+}
+
+void Time::Reset(int h, int m)
+{
+    hours = h;
+    minutes = m;
+}
+
+const Time Time::Sum(const Time & t) const
+{
+    Time sum;
+    sum.minutes = minutes + t.minutes;
+    sum.hours = hours + t.hours + sum.minutes / 60;
+    sum.minutes %= 60;
+    return sum;
+}
+
+void Time::Show() const
+{
+    std::cout << hours << " hours, " << minutes << " minutes";
+}

+ 19 - 0
CPPlusV6/Chapter 11/mytime0.h

@@ -0,0 +1,19 @@
+// mytime0.h -- Time class before operator overloading
+#ifndef MYTIME0_H_
+#define MYTIME0_H_
+
+class Time
+{
+private:
+    int hours;
+    int minutes;
+public:
+    Time();
+    Time(int h, int m = 0);
+    void AddMin(int m);
+    void AddHr(int h);
+    void Reset(int h = 0, int m = 0);
+    const Time Sum(const Time & t) const;
+    void Show() const;
+};
+#endif

+ 46 - 0
CPPlusV6/Chapter 11/mytime1.cpp

@@ -0,0 +1,46 @@
+// mytime1.cpp  -- implementing Time methods
+#include <iostream>
+#include "mytime1.h"
+
+Time::Time()
+{
+    hours = minutes = 0;
+}
+
+Time::Time(int h, int m )
+{
+    hours = h;
+    minutes = m;
+}
+
+void Time::AddMin(int m)
+{
+    minutes += m;
+    hours += minutes / 60;
+    minutes %= 60;
+}
+
+void Time::AddHr(int h)
+{
+    hours += h;
+}
+
+void Time::Reset(int h, int m)
+{
+    hours = h;
+    minutes = m;
+}
+
+Time Time::operator+(const Time & t) const
+{
+    Time sum;
+    sum.minutes = minutes + t.minutes;
+    sum.hours = hours + t.hours + sum.minutes / 60;
+    sum.minutes %= 60;
+    return sum;
+}
+
+void Time::Show() const
+{
+    std::cout << hours << " hours, " << minutes << " minutes";
+}

+ 19 - 0
CPPlusV6/Chapter 11/mytime1.h

@@ -0,0 +1,19 @@
+// mytime1.h -- Time class before operator overloading
+#ifndef MYTIME1_H_
+#define MYTIME1_H_
+
+class Time
+{
+private:
+    int hours;
+    int minutes;
+public:
+    Time();
+    Time(int h, int m = 0);
+    void AddMin(int m);
+    void AddHr(int h);
+    void Reset(int h = 0, int m = 0);
+    Time operator+(const Time & t) const;
+    void Show() const;
+};
+#endif

+ 65 - 0
CPPlusV6/Chapter 11/mytime2.cpp

@@ -0,0 +1,65 @@
+// mytime2.cpp  -- implementing Time methods
+#include <iostream>
+#include "mytime2.h"
+
+Time::Time()
+{
+    hours = minutes = 0;
+}
+
+Time::Time(int h, int m )
+{
+    hours = h;
+    minutes = m;
+}
+
+void Time::AddMin(int m)
+{
+    minutes += m;
+    hours += minutes / 60;
+    minutes %= 60;
+}
+void Time::AddHr(int h)
+{
+    hours += h;
+}
+
+void Time::Reset(int h, int m)
+{
+    hours = h;
+    minutes = m;
+}
+
+Time Time::operator+(const Time & t) const
+{
+    Time sum;
+    sum.minutes = minutes + t.minutes;
+    sum.hours = hours + t.hours + sum.minutes / 60;
+    sum.minutes %= 60;
+    return sum;
+}
+
+Time Time::operator-(const Time & t) const
+{
+    Time diff;
+    int tot1, tot2;
+    tot1 = t.minutes + 60 * t.hours;
+    tot2 = minutes + 60 * hours;
+    diff.minutes = (tot2 - tot1) % 60;
+    diff.hours = (tot2 - tot1) / 60;
+    return diff;
+}
+
+Time Time::operator*(double mult) const
+{
+    Time result;
+    long totalminutes = hours * mult * 60 + minutes * mult;
+    result.hours = totalminutes / 60;
+    result.minutes = totalminutes % 60;
+    return result;
+}
+
+void Time::Show() const
+{
+    std::cout << hours << " hours, " << minutes << " minutes";
+}

+ 21 - 0
CPPlusV6/Chapter 11/mytime2.h

@@ -0,0 +1,21 @@
+// mytime2.h -- Time class after operator overloading
+#ifndef MYTIME2_H_
+#define MYTIME2_H_
+
+class Time
+{
+private:
+    int hours;
+    int minutes;
+public:
+    Time();
+    Time(int h, int m = 0);
+    void AddMin(int m);
+    void AddHr(int h);
+    void Reset(int h = 0, int m = 0);
+    Time operator+(const Time & t) const;
+    Time operator-(const Time & t) const;
+    Time operator*(double n) const;
+    void Show() const;
+};
+#endif

+ 66 - 0
CPPlusV6/Chapter 11/mytime3.cpp

@@ -0,0 +1,66 @@
+// mytime3.cpp  -- implementing Time methods
+#include "mytime3.h"
+
+Time::Time()
+{
+    hours = minutes = 0;
+}
+
+Time::Time(int h, int m )
+{
+    hours = h;
+    minutes = m;
+}
+
+void Time::AddMin(int m)
+{
+    minutes += m;
+    hours += minutes / 60;
+    minutes %= 60;
+}
+
+void Time::AddHr(int h)
+{
+    hours += h;
+}
+
+void Time::Reset(int h, int m)
+{
+    hours = h;
+    minutes = m;
+}
+
+Time Time::operator+(const Time & t) const
+{
+    Time sum;
+    sum.minutes = minutes + t.minutes;
+    sum.hours = hours + t.hours + sum.minutes / 60;
+    sum.minutes %= 60;
+    return sum;
+}
+
+Time Time::operator-(const Time & t) const
+{
+    Time diff;
+    int tot1, tot2;
+    tot1 = t.minutes + 60 * t.hours;
+    tot2 = minutes + 60 * hours;
+    diff.minutes = (tot2 - tot1) % 60;
+    diff.hours = (tot2 - tot1) / 60;
+    return diff;
+}
+
+Time Time::operator*(double mult) const
+{
+    Time result;
+    long totalminutes = hours * mult * 60 + minutes * mult;
+    result.hours = totalminutes / 60;
+    result.minutes = totalminutes % 60;
+    return result;
+}
+
+std::ostream & operator<<(std::ostream & os, const Time & t)
+{
+    os << t.hours << " hours, " << t.minutes << " minutes";
+    return os; 
+}

+ 25 - 0
CPPlusV6/Chapter 11/mytime3.h

@@ -0,0 +1,25 @@
+// mytime3.h -- Time class with friends
+#ifndef MYTIME3_H_
+#define MYTIME3_H_
+#include <iostream>
+
+class Time
+{
+private:
+    int hours;
+    int minutes;
+public:
+    Time();
+    Time(int h, int m = 0);
+    void AddMin(int m);
+    void AddHr(int h);
+    void Reset(int h = 0, int m = 0);
+    Time operator+(const Time & t) const;
+    Time operator-(const Time & t) const;
+    Time operator*(double n) const;
+    friend Time operator*(double m, const Time & t)
+        { return t * m; }   // inline definition
+    friend std::ostream & operator<<(std::ostream & os, const Time & t);
+
+};
+#endif

+ 51 - 0
CPPlusV6/Chapter 11/randwalk.cpp

@@ -0,0 +1,51 @@
+// randwalk.cpp -- using the Vector class
+// compile with the vect.cpp file
+#include <iostream>
+#include <cstdlib>      // rand(), srand() prototypes
+#include <ctime>        // time() prototype
+#include "vect.h"
+int main()
+{
+    using namespace std;
+    using VECTOR::Vector;
+    srand(time(0));     // seed random-number generator
+    double direction;
+    Vector step;
+    Vector result(0.0, 0.0);
+    unsigned long steps = 0;
+    double target;
+    double dstep;
+    cout << "Enter target distance (q to quit): ";
+    while (cin >> target)
+    {
+        cout << "Enter step length: ";
+        if (!(cin >> dstep))
+            break;
+
+        while (result.magval() < target)
+        {
+            direction = rand() % 360;
+            step.reset(dstep, direction, POL);
+            result = result + step;
+            steps++;
+        }
+        cout << "After " << steps << " steps, the subject "
+            "has the following location:\n";
+        cout << result << endl;
+        result.polar_mode();
+        cout << " or\n" << result << endl;
+        cout << "Average outward distance per step = "
+            << result.magval()/steps << endl;
+        steps = 0;
+        result.reset(0.0, 0.0);
+        cout << "Enter target distance (q to quit): ";
+    }
+    cout << "Bye!\n";
+/* keep window open
+    cin.clear();
+    while (cin.get() != '\n')
+        continue;
+    cin.get();
+*/
+    return 0; 
+}

+ 40 - 0
CPPlusV6/Chapter 11/stone.cpp

@@ -0,0 +1,40 @@
+// stone.cpp -- user-defined conversions
+// compile with stonewt.cpp
+#include <iostream>
+using std::cout;
+#include "stonewt.h"
+void display(const Stonewt & st, int n);
+int main()
+{
+    Stonewt incognito = 275; // uses constructor to initialize
+    Stonewt wolfe(285.7);    // same as Stonewt wolfe = 285.7;
+    Stonewt taft(21, 8);
+
+    cout << "The celebrity weighed ";
+    incognito.show_stn();
+    cout << "The detective weighed ";
+    wolfe.show_stn();
+    cout << "The President weighed ";
+    taft.show_lbs();
+    incognito = 276.8;      // uses constructor for conversion
+    taft = 325;             // same as taft = Stonewt(325);
+    cout << "After dinner, the celebrity weighed ";
+    incognito.show_stn();
+    cout << "After dinner, the President weighed ";
+    taft.show_lbs();
+    display(taft, 2);
+    cout << "The wrestler weighed even more.\n";
+    display(422, 2);
+    cout << "No stone left unearned\n";
+    // std::cin.get();
+    return 0;
+}
+
+void display(const Stonewt & st, int n)
+{
+    for (int i = 0; i < n; i++)
+    {
+        cout << "Wow! ";
+        st.show_stn();
+    }
+}

+ 17 - 0
CPPlusV6/Chapter 11/stone1.cpp

@@ -0,0 +1,17 @@
+// stone1.cpp -- user-defined conversion functions
+// compile with stonewt1.cpp
+#include <iostream>
+#include "stonewt1.h"
+
+int main()
+{
+    using std::cout;
+    Stonewt poppins(9,2.8);     // 9 stone, 2.8 pounds
+    double p_wt = poppins;      // implicit conversion
+    cout << "Convert to double => ";
+    cout << "Poppins: " << p_wt << " pounds.\n";
+    cout << "Convert to int => ";
+    cout << "Poppins: " << int (poppins) << " pounds.\n";
+	// std::cin.get();
+    return 0; 
+}

+ 41 - 0
CPPlusV6/Chapter 11/stonewt.cpp

@@ -0,0 +1,41 @@
+// stonewt.cpp -- Stonewt methods
+#include <iostream>
+using std::cout;
+#include "stonewt.h"
+
+// construct Stonewt object from double value
+Stonewt::Stonewt(double lbs)
+{
+    stone = int (lbs) / Lbs_per_stn;    // integer division
+    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
+    pounds = lbs;
+}
+
+// construct Stonewt object from stone, double values
+Stonewt::Stonewt(int stn, double lbs)
+{
+    stone = stn;
+    pds_left = lbs;
+    pounds =  stn * Lbs_per_stn +lbs;
+}
+
+Stonewt::Stonewt()          // default constructor, wt = 0
+{
+    stone = pounds = pds_left = 0;
+}
+
+Stonewt::~Stonewt()         // destructor
+{
+}
+
+// show weight in stones
+void Stonewt::show_stn() const
+{
+    cout << stone << " stone, " << pds_left << " pounds\n";
+}
+
+// show weight in pounds
+void Stonewt::show_lbs() const
+{
+    cout << pounds << " pounds\n";
+}

+ 19 - 0
CPPlusV6/Chapter 11/stonewt.h

@@ -0,0 +1,19 @@
+// stonewt.h -- definition for the Stonewt class
+#ifndef STONEWT_H_
+#define STONEWT_H_
+class Stonewt
+{
+private:
+    enum {Lbs_per_stn = 14};      // pounds per stone
+    int stone;                    // whole stones
+    double pds_left;              // fractional pounds
+    double pounds;                // entire weight in pounds
+public:
+    Stonewt(double lbs);          // constructor for double pounds
+    Stonewt(int stn, double lbs); // constructor for stone, lbs
+    Stonewt();                    // default constructor
+    ~Stonewt();
+    void show_lbs() const;        // show weight in pounds format
+    void show_stn() const;        // show weight in stone format
+};
+#endif

+ 54 - 0
CPPlusV6/Chapter 11/stonewt1.cpp

@@ -0,0 +1,54 @@
+// stonewt1.cpp -- Stonewt class methods + conversion functions
+#include <iostream>
+using std::cout;
+#include "stonewt1.h"
+
+// construct Stonewt object from double value
+Stonewt::Stonewt(double lbs)
+{
+    stone = int (lbs) / Lbs_per_stn;    // integer division
+    pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
+    pounds = lbs;
+}
+
+// construct Stonewt object from stone, double values
+Stonewt::Stonewt(int stn, double lbs)
+{
+    stone = stn;
+    pds_left = lbs;
+    pounds =  stn * Lbs_per_stn +lbs;
+}
+
+Stonewt::Stonewt()          // default constructor, wt = 0
+{
+    stone = pounds = pds_left = 0;
+}
+
+Stonewt::~Stonewt()         // destructor
+{
+}
+
+// show weight in stones
+void Stonewt::show_stn() const
+{
+    cout << stone << " stone, " << pds_left << " pounds\n";
+}
+
+// show weight in pounds
+void Stonewt::show_lbs() const
+{
+    cout << pounds << " pounds\n";
+}
+
+// conversion functions
+Stonewt::operator int() const
+{
+
+    return int (pounds + 0.5);
+
+}
+
+Stonewt::operator double()const
+{
+    return pounds; 
+}

+ 22 - 0
CPPlusV6/Chapter 11/stonewt1.h

@@ -0,0 +1,22 @@
+// stonewt1.h -- revised definition for the Stonewt class
+#ifndef STONEWT1_H_
+#define STONEWT1_H_
+class Stonewt
+{
+private:
+    enum {Lbs_per_stn = 14};      // pounds per stone
+    int stone;                    // whole stones
+    double pds_left;              // fractional pounds
+    double pounds;                // entire weight in pounds
+public:
+    Stonewt(double lbs);          // construct from double pounds
+    Stonewt(int stn, double lbs); // construct from stone, lbs
+    Stonewt();                    // default constructor
+    ~Stonewt();
+    void show_lbs() const;        // show weight in pounds format
+    void show_stn() const;        // show weight in stone format
+// conversion functions
+    operator int() const;
+    operator double() const;
+};
+#endif

+ 33 - 0
CPPlusV6/Chapter 11/usetime0.cpp

@@ -0,0 +1,33 @@
+// usetime0.cpp -- using the first draft of the Time class
+// compile usetime0.cpp and mytime0.cpp together
+#include <iostream>
+#include "mytime0.h"
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+    Time planning;
+    Time coding(2, 40);
+    Time fixing(5, 55);
+    Time total;
+
+    cout << "planning time = ";
+    planning.Show();
+    cout << endl;
+ 
+    cout << "coding time = ";
+    coding.Show();
+    cout << endl;
+    
+    cout << "fixing time = ";
+    fixing.Show();
+    cout << endl;
+
+    total = coding.Sum(fixing);
+    cout << "coding.Sum(fixing) = ";
+  	total.Show();
+    cout << endl;
+    // std::cin.get();
+    return 0;
+}

+ 44 - 0
CPPlusV6/Chapter 11/usetime1.cpp

@@ -0,0 +1,44 @@
+// usetime1.cpp -- using the second draft of the Time class
+// compile usetime1.cpp and mytime1.cpp together
+#include <iostream>
+#include "mytime1.h"
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+    Time planning;
+    Time coding(2, 40);
+    Time fixing(5, 55);
+    Time total;
+
+    cout << "planning time = ";
+    planning.Show();
+    cout << endl;
+ 
+    cout << "coding time = ";
+    coding.Show();
+    cout << endl;
+    
+    cout << "fixing time = ";
+    fixing.Show();
+    cout << endl;
+
+    total = coding + fixing;
+    // operator notation
+    cout << "coding + fixing = ";
+    total.Show();
+    cout << endl;
+
+    Time morefixing(3, 28);
+    cout << "more fixing time = ";
+    morefixing.Show();
+    cout << endl;
+    total = morefixing.operator+(total);
+    // function notation
+    cout << "morefixing.operator+(total) = ";
+    total.Show();
+    cout << endl;
+    // std::cin.get();
+    return 0;
+}

+ 40 - 0
CPPlusV6/Chapter 11/usetime2.cpp

@@ -0,0 +1,40 @@
+// usetime2.cpp -- using the third draft of the Time class
+// compile usetime2.cpp and mytime2.cpp together
+#include <iostream>
+#include "mytime2.h"
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+    Time weeding(4, 35);
+    Time waxing(2, 47);
+    Time total;
+    Time diff;
+    Time adjusted;
+
+    cout << "weeding time = ";
+    weeding.Show();
+    cout << endl;
+ 
+    cout << "waxing time = ";
+    waxing.Show();
+    cout << endl;
+    
+    cout << "total work time = ";
+    total = weeding + waxing;   // use operator+()
+    total.Show();
+    cout << endl;
+
+    diff = weeding - waxing;    // use operator-()
+    cout << "weeding time - waxing time = ";
+    diff.Show();
+    cout << endl;
+
+    adjusted = total * 1.5;      // use operator+()
+    cout << "adjusted work time = ";
+    adjusted.Show();
+    cout << endl;
+    // std::cin.get();    
+    return 0;
+}

+ 23 - 0
CPPlusV6/Chapter 11/usetime3.cpp

@@ -0,0 +1,23 @@
+//usetime3.cpp -- using the fourth draft of the Time class
+// compile usetime3.cpp and mytime3.cpp together
+#include <iostream>
+#include "mytime3.h"
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+    Time aida(3, 35);
+    Time tosca(2, 48);
+    Time temp;
+
+    cout << "Aida and Tosca:\n";
+    cout << aida<<"; " << tosca << endl;
+    temp = aida + tosca;     // operator+()
+    cout << "Aida + Tosca: " << temp << endl;
+    temp = aida* 1.17;  // member operator*()
+    cout << "Aida * 1.17: " << temp << endl;
+    cout << "10.0 * Tosca: " << 10.0 * tosca << endl;
+	// std::cin.get();
+    return 0; 
+}

+ 170 - 0
CPPlusV6/Chapter 11/vect.cpp

@@ -0,0 +1,170 @@
+// vect.cpp -- methods for the Vector class
+#include <cmath>
+#include "vect.h"   // includes <iostream>
+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
+    const double Rad_to_deg = 45.0 / atan(1.0);
+    // should be about 57.2957795130823
+
+    // private methods
+    // calculates magnitude from x and y
+    void Vector::set_mag()
+    {
+        mag = sqrt(x * x + y * y);
+    }
+
+    void Vector::set_ang()
+    {
+        if (x == 0.0 && y == 0.0)
+            ang = 0.0;
+        else
+            ang = atan2(y, x);
+    }
+
+    // set x from polar coordinate
+    void Vector::set_x()
+    {
+        x = mag * cos(ang);
+    }
+
+    // set y from polar coordinate
+    void Vector::set_y()
+    {
+        y = mag * sin(ang);
+    }
+
+    // public methods
+    Vector::Vector()             // default constructor
+    {
+        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()    // set to polar mode
+    {
+        mode = POL;
+    }
+
+    void Vector::rect_mode()     // 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-() const
+    {
+        return Vector(-x, -y);
+    }
+
+    // multiply vector by n
+    Vector Vector::operator*(double n) const
+    {
+        return Vector(n * x, n * y);
+    }
+
+    // friend methods
+    // multiply 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

+ 45 - 0
CPPlusV6/Chapter 11/vect.h

@@ -0,0 +1,45 @@
+// vect.h -- Vector class with <<, mode state
+#ifndef VECTOR_H_
+#define VECTOR_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 vector
+        double ang;        // direction of vector in degrees
+        Mode mode;         // RECT or POL
+    // private methods for setting values
+        void set_mag();
+        void set_ang();
+        void set_x();
+        void set_y();
+    public:
+       Vector();
+        Vector(double n1, double n2, Mode form = RECT);
+        void reset(double n1, double n2, Mode form = RECT);
+        ~Vector();
+        double xval() const {return x;}       // report x value
+        double yval() const {return y;}       // report y value
+        double magval() const {return mag;}   // report magnitude
+        double angval() const {return ang;}   // report angle
+        void polar_mode();                    // set mode to POL
+        void rect_mode();                     // set mode to RECT
+    // operator overloading
+        Vector operator+(const Vector & b) const;
+        Vector operator-(const Vector & b) const;
+        Vector operator-() 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

+ 99 - 0
CPPlusV6/Chapter 12/bank.cpp

@@ -0,0 +1,99 @@
+// 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 up
+    std::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 people
+
+    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 = 0;     //  turned away by full queue
+    long customers = 0;     //  joined the queue
+    long served = 0;        //  served during the simulation
+    long sum_line = 0;      //  cumulative line length
+    int wait_time = 0;      //  time until autoteller is free
+    long line_wait = 0;     //  cumulative time in line
+
+
+// running the simulation
+    for (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 arrival
+                line.enqueue(temp); // add newcomer to line
+            }
+        }
+        if (wait_time <= 0 && !line.isempty())
+        {
+            line.dequeue (temp);      // attend next customer
+            wait_time = temp.ptime(); // for wait_time minutes
+            line_wait += cycle - temp.when();
+            served++;
+        }
+        if (wait_time > 0)
+            wait_time--;
+        sum_line += line.queuecount();
+    }
+
+// reporting results
+    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";
+    }
+    else
+        cout << "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); 
+}

+ 51 - 0
CPPlusV6/Chapter 12/placenew1.cpp

@@ -0,0 +1,51 @@
+// placenew1.cpp  -- new, placement new, no delete
+#include <iostream>
+#include <string>
+#include <new>
+using namespace std;
+const int BUF = 512;
+
+class JustTesting
+{
+private:
+    string words;
+    int number;
+public:
+    JustTesting(const string & s = "Just Testing", int n = 0) 
+    {words = s; number = n; cout << words << " constructed\n"; }
+    ~JustTesting() { cout << words << " destroyed\n";}
+    void Show() const { cout << words << ", " << number << endl;}
+};
+int main()
+{
+    char * buffer = new char[BUF];       // get a block of memory
+
+    JustTesting *pc1, *pc2;
+
+    pc1 = new (buffer) JustTesting;      // place object in buffer
+    pc2 = new JustTesting("Heap1", 20);  // place object on heap
+    
+    cout << "Memory block addresses:\n" << "buffer: "
+        << (void *) buffer << "    heap: " << pc2 <<endl;
+    cout << "Memory contents:\n";
+    cout << pc1 << ": ";
+    pc1->Show();
+    cout << pc2 << ": ";
+    pc2->Show();
+
+    JustTesting *pc3, *pc4;
+    pc3 = new (buffer) JustTesting("Bad Idea", 6);
+    pc4 = new JustTesting("Heap2", 10);
+    cout << "Memory contents:\n";
+    cout << pc3 << ": ";
+    pc3->Show();
+    cout << pc4 << ": ";
+    pc4->Show();
+    
+    delete pc2;                          // free Heap1         
+    delete pc4;                          // free Heap2
+    delete [] buffer;                    // free buffer
+    cout << "Done\n";
+    // std::cin.get();
+    return 0;
+}

+ 56 - 0
CPPlusV6/Chapter 12/placenew2.cpp

@@ -0,0 +1,56 @@
+// placenew2.cpp  -- new, placement new, no delete
+#include <iostream>
+#include <string>
+#include <new>
+using namespace std;
+const int BUF = 512;
+
+class JustTesting
+{
+private:
+    string words;
+    int number;
+public:
+    JustTesting(const string & s = "Just Testing", int n = 0) 
+    {words = s; number = n; cout << words << " constructed\n"; }
+    ~JustTesting() { cout << words << " destroyed\n";}
+    void Show() const { cout << words << ", " << number << endl;}
+};
+int main()
+{
+    char * buffer = new char[BUF];       // get a block of memory
+
+    JustTesting *pc1, *pc2;
+
+    pc1 = new (buffer) JustTesting;      // place object in buffer
+    pc2 = new JustTesting("Heap1", 20);  // place object on heap
+    
+    cout << "Memory block addresses:\n" << "buffer: "
+        << (void *) buffer << "    heap: " << pc2 <<endl;
+    cout << "Memory contents:\n";
+    cout << pc1 << ": ";
+    pc1->Show();
+    cout << pc2 << ": ";
+    pc2->Show();
+
+    JustTesting *pc3, *pc4;
+// fix placement new location
+    pc3 = new (buffer + sizeof (JustTesting))
+                JustTesting("Better Idea", 6);
+    pc4 = new JustTesting("Heap2", 10);
+    
+    cout << "Memory contents:\n";
+    cout << pc3 << ": ";
+    pc3->Show();
+    cout << pc4 << ": ";
+    pc4->Show();
+    
+    delete pc2;           // free Heap1         
+    delete pc4;           // free Heap2
+// explicitly destroy placement new objects
+    pc3->~JustTesting();  // destroy object pointed to by pc3
+    pc1->~JustTesting();  // destroy object pointed to by pc1
+    delete [] buffer;     // free buffer
+    // std::cin.get();
+    return 0;
+}

+ 80 - 0
CPPlusV6/Chapter 12/queue.cpp

@@ -0,0 +1,80 @@
+// 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 nullptr
+    items = 0;
+}
+
+Queue::~Queue()
+{
+    Node * temp;
+    while (front != NULL)   // while queue is not yet empty
+    {
+        temp = front;       // save address of front item
+        front = front->next;// reset pointer to next item
+        delete 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 exception
+    add->item = item;       // set node pointers
+    add->next = NULL;       // or nullptr;
+    items++;
+    if (front == NULL)      // if queue is empty,
+        front = add;        // place item at front
+    else
+        rear->next = add;   // else place at rear
+    rear = add;             // have rear point to new node
+    return 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 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 == 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; 
+}

+ 43 - 0
CPPlusV6/Chapter 12/queue.h

@@ -0,0 +1,43 @@
+// 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 customer
+    int 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 class
+    struct Node { Item item; struct Node * next;};
+    enum {Q_SIZE = 10};
+// private class members
+    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;    // maximum number of items in Queue
+    // preemptive definitions to prevent public copying
+    Queue(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 end
+    bool dequeue(Item &item);       // remove item from front
+};
+#endif

+ 62 - 0
CPPlusV6/Chapter 12/sayings1.cpp

@@ -0,0 +1,62 @@
+// sayings1.cpp -- using expanded String class
+// compile with string1.cpp
+#include <iostream>
+#include "string1.h" 
+const int ArSize = 10;
+const int MaxLen =81;
+int main()
+{
+    using std::cout;
+    using std::cin;
+    using std::endl;
+    String name;
+    cout <<"Hi, what's your name?\n>> ";
+    cin >> name;
+
+    cout << name << ", please enter up to " << ArSize
+         << " short sayings <empty line to quit>:\n";
+    String sayings[ArSize];     // array of objects
+    char temp[MaxLen];          // temporary string storage
+    int i;
+    for (i = 0; i < ArSize; i++)
+    {
+        cout << i+1 << ": ";
+        cin.get(temp, MaxLen);
+        while (cin && cin.get() != '\n')
+            continue;
+        if (!cin || temp[0] == '\0')    // empty line?
+            break;              // i not incremented
+        else
+            sayings[i] = temp;  // overloaded assignment
+    }
+    int total = i;              // total # of lines read
+
+    if ( total > 0)
+    {
+        cout << "Here are your sayings:\n";
+        for (i = 0; i < total; i++)
+            cout << sayings[i][0] << ": " << sayings[i] << endl;
+
+        int shortest = 0;
+        int first = 0;
+        for (i = 1; i < total; i++)
+        {
+            if (sayings[i].length() < sayings[shortest].length())
+                shortest = i;
+            if (sayings[i] < sayings[first])
+                first = i;
+        }
+        cout << "Shortest saying:\n" << sayings[shortest] << endl;;
+        cout << "First alphabetically:\n" << sayings[first] << endl;
+        cout << "This program used "<< String::HowMany() 
+             << " String objects. Bye.\n";
+    }
+    else
+        cout << "No input! Bye.\n";
+// keep window open 
+/*    if (!cin)
+        cin.clear();
+    while (cin.get() != '\n')
+        continue; */ 
+   return 0; 
+}

+ 71 - 0
CPPlusV6/Chapter 12/sayings2.cpp

@@ -0,0 +1,71 @@
+// sayings2.cpp -- using pointers to objects
+// compile with string1.cpp
+#include <iostream>
+#include <cstdlib>      // (or stdlib.h) for rand(), srand()
+#include <ctime>        // (or time.h) for time()
+#include "string1.h"
+const int ArSize = 10;
+const int MaxLen = 81;
+int main()
+{
+    using namespace std;
+    String name;
+    cout <<"Hi, what's your name?\n>> ";
+    cin >> name;
+
+    cout << name << ", please enter up to " << ArSize
+         << " short sayings <empty line to quit>:\n";
+    String sayings[ArSize];
+    char temp[MaxLen];               // temporary string storage
+    int i;
+    for (i = 0; i < ArSize; i++)
+    {
+        cout << i+1 << ": ";
+        cin.get(temp, MaxLen);
+        while (cin && cin.get() != '\n')
+            continue;
+        if (!cin || temp[0] == '\0') // empty line?
+            break;                   // i not incremented
+        else
+            sayings[i] = temp;       // overloaded assignment
+    }
+    int total = i;                   // total # of lines read
+
+    if (total > 0)
+    {
+        cout << "Here are your sayings:\n";
+        for (i = 0; i < total; i++)
+            cout << sayings[i] << "\n";
+
+    // use pointers to keep track of shortest, first strings
+        String * shortest = &sayings[0]; // initialize to first object
+        String * first = &sayings[0];
+        for (i = 1; i < total; i++)
+        {
+            if (sayings[i].length() < shortest->length())
+                shortest = &sayings[i];
+            if (sayings[i] < *first)     // compare values
+                first = &sayings[i];     // assign address
+        }
+        cout << "Shortest saying:\n" << * shortest << endl;
+        cout << "First alphabetically:\n" << * first << endl;
+
+        srand(time(0));
+        int choice = rand() % total; // pick index at random
+    // use new to create, initialize new String object
+        String * favorite = new String(sayings[choice]);
+        cout << "My favorite saying:\n" << *favorite << endl;
+        delete favorite;
+    }
+    else
+        cout << "Not much to say, eh?\n";
+    cout << "Bye.\n";
+// keep window open
+/*    if (!cin)
+        cin.clear();
+    while (cin.get() != '\n')
+        continue;
+    cin.get();
+*/
+    return 0; 
+}

+ 118 - 0
CPPlusV6/Chapter 12/string1.cpp

@@ -0,0 +1,118 @@
+// string1.cpp -- String class methods
+#include <cstring>                 // string.h for some
+#include "string1.h"               // includes <iostream>
+using std::cin;
+using std::cout;
+
+// initializing static class member
+
+int String::num_strings = 0;
+
+// static method
+int String::HowMany()
+{
+    return num_strings;
+}
+
+// class methods
+String::String(const char * s)     // construct String from C string
+{
+    len = std::strlen(s);          // set size
+    str = new char[len + 1];       // allot storage
+    std::strcpy(str, s);           // initialize pointer
+    num_strings++;                 // set object count
+}
+
+String::String()                   // default constructor
+{
+    len = 4;
+    str = new char[1];
+    str[0] = '\0';                 // default string
+    num_strings++;
+}
+
+String::String(const String & st)
+{
+    num_strings++;             // handle static member update
+    len = st.len;              // same length
+    str = new char [len + 1];  // allot space
+    std::strcpy(str, st.str);  // copy string to new location
+}
+
+String::~String()                     // necessary destructor
+{
+    --num_strings;                    // required
+    delete [] str;                    // required
+}
+
+// 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 + 1];
+    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 + 1];
+    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];
+}
+
+// overloaded operator friends
+
+bool operator<(const String &st1, const String &st2)
+{
+    return (std::strcmp(st1.str, st2.str) < 0);
+}
+
+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) == 0);
+}
+
+    // simple String output
+ostream & operator<<(ostream & os, const String & st)
+{
+    os << st.str;
+    return os; 
+}
+
+    // quick and dirty String input
+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; 
+}

+ 37 - 0
CPPlusV6/Chapter 12/string1.h

@@ -0,0 +1,37 @@
+// string1.h -- fixed and augmented string class definition
+
+#ifndef STRING1_H_
+#define STRING1_H_
+#include <iostream>
+using std::ostream;
+using std::istream;
+
+class String
+{
+private:
+    char * str;             // pointer to string
+    int len;                // length of string
+    static int num_strings; // number of objects
+    static const int CINLIM = 80;  // cin input limit
+public:
+// constructors and other methods
+    String(const char * s); // constructor
+    String();               // default constructor
+    String(const String &); // copy constructor
+    ~String();              // destructor
+    int length () const { return len; }
+// overloaded operator methods    
+    String & operator=(const String &);
+    String & operator=(const char *);
+    char & operator[](int i);
+    const char & operator[](int i) const;
+// overloaded operator friends
+    friend bool operator<(const String &st, const String &st2);
+    friend bool operator>(const String &st1, const String &st2);
+    friend bool operator==(const String &st, const String &st2);
+    friend ostream & operator<<(ostream & os, const String & st);
+    friend istream & operator>>(istream & is, String & st);
+// static function
+    static int HowMany();
+};
+#endif

+ 44 - 0
CPPlusV6/Chapter 12/strngbad.cpp

@@ -0,0 +1,44 @@
+// strngbad.cpp -- StringBad class methods
+#include <cstring>                    // string.h for some
+#include "strngbad.h"
+using std::cout;
+
+// initializing static class member
+int StringBad::num_strings = 0;
+
+// class methods
+
+// construct StringBad from C string
+StringBad::StringBad(const char * s)
+{
+    len = std::strlen(s);             // set size
+    str = new char[len + 1];          // allot storage
+    std::strcpy(str, s);              // initialize pointer
+    num_strings++;                    // set object count
+    cout << num_strings << ": \"" << str
+         << "\" object created\n";    // For Your Information
+}
+
+StringBad::StringBad()                // default constructor
+{
+    len = 4;
+    str = new char[4];
+    std::strcpy(str, "C++");          // default string
+    num_strings++;
+    cout << num_strings << ": \"" << str
+         << "\" default object created\n";  // FYI
+}
+
+StringBad::~StringBad()               // necessary destructor
+{
+    cout << "\"" << str << "\" object deleted, ";    // FYI
+    --num_strings;                    // required
+    cout << num_strings << " left\n"; // FYI
+    delete [] str;                    // required
+}
+
+std::ostream & operator<<(std::ostream & os, const StringBad & st)
+{
+    os << st.str;
+    return os; 
+}

+ 19 - 0
CPPlusV6/Chapter 12/strngbad.h

@@ -0,0 +1,19 @@
+// strngbad.h -- flawed string class definition
+#include <iostream>
+#ifndef STRNGBAD_H_
+#define STRNGBAD_H_
+class StringBad
+{
+private:
+    char * str;                // pointer to string
+    int len;                   // length of string
+    static int num_strings;    // number of objects
+public:
+    StringBad(const char * s); // constructor
+    StringBad();               // default constructor
+    ~StringBad();              // destructor
+// friend function
+    friend std::ostream & operator<<(std::ostream & os, 
+                       const StringBad & st);
+};
+#endif

+ 49 - 0
CPPlusV6/Chapter 12/vegnews.cpp

@@ -0,0 +1,49 @@
+// vegnews.cpp -- using new and delete with classes
+// compile with strngbad.cpp
+#include <iostream>
+using std::cout;
+#include "strngbad.h"
+
+void callme1(StringBad &);  // pass by reference
+void callme2(StringBad);    // pass by value
+
+int main()
+{
+    using std::endl;
+    {
+        cout << "Starting an inner block.\n";
+        StringBad headline1("Celery Stalks at Midnight");
+        StringBad headline2("Lettuce Prey");
+        StringBad sports("Spinach Leaves Bowl for Dollars");
+        cout << "headline1: " << headline1 << endl;
+        cout << "headline2: " << headline2 << endl;
+        cout << "sports: " << sports << endl;
+        callme1(headline1);
+        cout << "headline1: " << headline1 << endl;
+        callme2(headline2);
+        cout << "headline2: " << headline2 << endl;
+        cout << "Initialize one object to another:\n";
+        StringBad sailor = sports;
+        cout << "sailor: " << sailor << endl;
+        cout << "Assign one object to another:\n";
+        StringBad knot;
+        knot = headline1;
+        cout << "knot: " << knot << endl; 
+        cout << "Exiting the block.\n";
+    }
+    cout << "End of main()\n";
+    // std::cin.get();
+    return 0;
+}
+
+void callme1(StringBad & rsb)
+{
+    cout << "String passed by reference:\n";
+    cout << "    \"" << rsb << "\"\n";
+}
+
+void callme2(StringBad sb)
+{
+    cout << "String passed by value:\n";
+    cout << "    \"" << sb << "\"\n";
+}

+ 122 - 0
CPPlusV6/Chapter 13/acctabc.cpp

@@ -0,0 +1,122 @@
+// acctabc.cpp -- bank account class methods
+#include <iostream>
+#include "acctabc.h"
+using std::cout;
+using std::ios_base;
+using std::endl;
+using std::string;
+
+// Abstract Base Class
+AcctABC::AcctABC(const string & s, long an, double bal)
+{
+    fullName = s;
+    acctNum = an;
+    balance = bal;
+}
+
+void AcctABC::Deposit(double amt)
+{
+    if (amt < 0)
+        cout << "Negative deposit not allowed; "
+             << "deposit is cancelled.\n";
+    else
+        balance += amt;
+}
+
+void AcctABC::Withdraw(double amt)
+{
+    balance -= amt;
+}
+
+// protected methods for formatting
+AcctABC::Formatting AcctABC::SetFormat() const
+{
+ // set up ###.## format
+    Formatting f;
+    f.flag = 
+        cout.setf(ios_base::fixed, ios_base::floatfield);
+    f.pr = cout.precision(2);
+    return f; 
+}
+
+void AcctABC::Restore(Formatting & f) const
+{
+    cout.setf(f.flag, ios_base::floatfield);
+    cout.precision(f.pr);
+}
+
+// Brass methods
+void Brass::Withdraw(double amt)
+{
+    if (amt < 0)
+        cout << "Withdrawal amount must be positive; "
+             << "withdrawal canceled.\n";
+    else if (amt <= Balance())
+        AcctABC::Withdraw(amt);
+    else
+        cout << "Withdrawal amount of $" << amt
+             << " exceeds your balance.\n"
+             << "Withdrawal canceled.\n";
+}
+
+void Brass::ViewAcct() const
+{
+   
+    Formatting f = SetFormat();
+    cout << "Brass Client: " << FullName() << endl;
+    cout << "Account Number: " << AcctNum() << endl;
+    cout << "Balance: $" << Balance() << endl;
+    Restore(f);
+}
+
+// BrassPlus Methods
+BrassPlus::BrassPlus(const string & s, long an, double bal,
+           double ml, double r) : AcctABC(s, an, bal)
+{
+    maxLoan = ml;
+    owesBank = 0.0;
+    rate = r; 
+}
+
+BrassPlus::BrassPlus(const Brass & ba, double ml, double r)
+           : AcctABC(ba)   // uses implicit copy constructor
+{
+    maxLoan = ml;
+    owesBank = 0.0;
+    rate = r;
+}
+
+void BrassPlus::ViewAcct() const
+{
+    Formatting f = SetFormat();
+
+    cout << "BrassPlus Client: " << FullName() << endl;
+    cout << "Account Number: " << AcctNum() << endl;
+    cout << "Balance: $" << Balance() << endl;
+    cout << "Maximum loan: $" << maxLoan << endl;
+    cout << "Owed to bank: $" << owesBank << endl;
+    cout.precision(3);
+    cout << "Loan Rate: " << 100 * rate << "%\n";
+    Restore(f);
+}
+
+void BrassPlus::Withdraw(double amt)
+{
+    Formatting f = SetFormat();
+
+    double bal = Balance();
+    if (amt <= bal)
+        AcctABC::Withdraw(amt);
+    else if ( amt <= bal + maxLoan - owesBank)
+    {
+        double advance = amt - bal;
+        owesBank += advance * (1.0 + rate);
+        cout << "Bank advance: $" << advance << endl;
+        cout << "Finance charge: $" << advance * rate << endl;
+        Deposit(advance);
+        AcctABC::Withdraw(amt);
+    }
+    else
+        cout << "Credit limit exceeded. Transaction cancelled.\n";
+    Restore(f); 
+}

+ 64 - 0
CPPlusV6/Chapter 13/acctabc.h

@@ -0,0 +1,64 @@
+// acctabc.h  -- bank account classes
+#ifndef ACCTABC_H_
+#define ACCTABC_H_
+#include <iostream>
+#include <string>
+
+// Abstract Base Class
+class AcctABC
+{
+private:
+    std::string fullName;
+    long acctNum;
+    double balance;
+protected:
+    struct Formatting 
+    {
+         std::ios_base::fmtflags flag;
+         std::streamsize pr;
+    };
+    const std::string & FullName() const {return fullName;}
+    long AcctNum() const {return acctNum;}
+    Formatting SetFormat() const;
+    void Restore(Formatting & f) const;
+public: 
+    AcctABC(const std::string & s = "Nullbody", long an = -1,
+                double bal = 0.0);
+    void Deposit(double amt) ;
+    virtual void Withdraw(double amt) = 0; // pure virtual function
+    double Balance() const {return balance;};
+    virtual void ViewAcct() const = 0;     // pure virtual function
+    virtual ~AcctABC() {}
+};
+
+// Brass Account Class
+class Brass :public AcctABC
+{
+public:
+    Brass(const std::string & s = "Nullbody", long an = -1,
+           double bal = 0.0) : AcctABC(s, an, bal) { }
+    virtual void Withdraw(double amt);
+    virtual void ViewAcct() const;
+    virtual ~Brass() {}
+};
+
+//Brass Plus Account Class
+class BrassPlus : public AcctABC
+{
+private:
+    double maxLoan;
+    double rate;
+    double owesBank;
+public:
+    BrassPlus(const std::string & s = "Nullbody", long an = -1,
+            double bal = 0.0, double ml = 500,
+            double r = 0.10);
+    BrassPlus(const Brass & ba, double ml = 500, double r = 0.1);
+    virtual void ViewAcct()const;
+    virtual void Withdraw(double amt);
+    void ResetMax(double m) { maxLoan = m; }
+    void ResetRate(double r) { rate = r; };
+    void ResetOwes() { owesBank = 0; }
+};
+
+#endif

+ 133 - 0
CPPlusV6/Chapter 13/brass.cpp

@@ -0,0 +1,133 @@
+// brass.cpp -- bank account class methods
+#include <iostream>
+#include "brass.h"
+using std::cout;
+using std::endl;
+using std::string;
+
+// formatting stuff
+typedef std::ios_base::fmtflags format;
+typedef std::streamsize precis;
+format setFormat();
+void restore(format f, precis p);
+
+// Brass methods
+
+Brass::Brass(const string & s, long an, double bal)
+{
+    fullName = s;
+    acctNum = an;
+    balance = bal;
+}
+
+void Brass::Deposit(double amt)
+{
+    if (amt < 0)
+        cout << "Negative deposit not allowed; "
+             << "deposit is cancelled.\n";
+    else
+        balance += amt;
+}
+
+void Brass::Withdraw(double amt)
+{
+    // set up ###.## format
+    format initialState = setFormat();
+    precis prec = cout.precision(2);
+
+    if (amt < 0)
+        cout << "Withdrawal amount must be positive; "
+
+             << "withdrawal canceled.\n";
+    else if (amt <= balance)
+        balance -= amt;
+    else
+        cout << "Withdrawal amount of $" << amt
+             << " exceeds your balance.\n"
+             << "Withdrawal canceled.\n";
+    restore(initialState, prec);
+}
+double Brass::Balance() const
+{
+    return balance;
+}
+
+void Brass::ViewAcct() const
+{
+     // set up ###.## format
+    format initialState = setFormat();
+    precis prec = cout.precision(2);
+    cout << "Client: " << fullName << endl;
+    cout << "Account Number: " << acctNum << endl;
+    cout << "Balance: $" << balance << endl;
+    restore(initialState, prec); // Restore original format
+}
+
+// BrassPlus Methods
+BrassPlus::BrassPlus(const string & s, long an, double bal,
+           double ml, double r) : Brass(s, an, bal)
+{
+    maxLoan = ml;
+    owesBank = 0.0;
+    rate = r;
+}
+
+BrassPlus::BrassPlus(const Brass & ba, double ml, double r)
+           : Brass(ba)   // uses implicit copy constructor
+{
+    maxLoan = ml;
+    owesBank = 0.0;
+    rate = r;
+}
+
+// redefine how ViewAcct() works
+void BrassPlus::ViewAcct() const
+{
+    // set up ###.## format
+    format initialState = setFormat();
+    precis prec = cout.precision(2);
+
+    Brass::ViewAcct();   // display base portion
+    cout << "Maximum loan: $" << maxLoan << endl;
+    cout << "Owed to bank: $" << owesBank << endl;
+    cout.precision(3);  // ###.### format
+    cout << "Loan Rate: " << 100 * rate << "%\n";
+    restore(initialState, prec); 
+}
+
+// redefine how Withdraw() works
+void BrassPlus::Withdraw(double amt)
+{
+    // set up ###.## format
+    format initialState = setFormat();
+    precis prec = cout.precision(2);
+
+    double bal = Balance();
+    if (amt <= bal)
+        Brass::Withdraw(amt);
+    else if ( amt <= bal + maxLoan - owesBank)
+    {
+        double advance = amt - bal;
+        owesBank += advance * (1.0 + rate);
+        cout << "Bank advance: $" << advance << endl;
+        cout << "Finance charge: $" << advance * rate << endl;
+        Deposit(advance);
+        Brass::Withdraw(amt);
+    }
+    else
+        cout << "Credit limit exceeded. Transaction cancelled.\n";
+    restore(initialState, prec); 
+}
+
+format setFormat()
+{
+    // set up ###.## format
+    return cout.setf(std::ios_base::fixed, 
+                std::ios_base::floatfield);
+} 
+
+void restore(format f, precis p)
+{
+    cout.setf(f, std::ios_base::floatfield);
+    cout.precision(p);
+}

+ 42 - 0
CPPlusV6/Chapter 13/brass.h

@@ -0,0 +1,42 @@
+// brass.h  -- bank account classes
+#ifndef BRASS_H_
+#define BRASS_H_
+#include <string>
+// Brass Account Class
+class Brass
+{
+private:
+    std::string fullName;
+    long acctNum;
+    double balance;
+public:
+    Brass(const std::string & s = "Nullbody", long an = -1,
+                double bal = 0.0);
+    void Deposit(double amt);
+    virtual void Withdraw(double amt);
+    double Balance() const;
+    virtual void ViewAcct() const;
+    virtual ~Brass() {}
+};
+
+//Brass Plus Account Class
+class BrassPlus : public Brass
+{
+private:
+    double maxLoan;
+    double rate;
+    double owesBank;
+public:
+    BrassPlus(const std::string & s = "Nullbody", long an = -1,
+            double bal = 0.0, double ml = 500,
+            double r = 0.11125);
+    BrassPlus(const Brass & ba, double ml = 500, 
+		                        double r = 0.11125);
+    virtual void ViewAcct()const;
+    virtual void Withdraw(double amt);
+    void ResetMax(double m) { maxLoan = m; }
+    void ResetRate(double r) { rate = r; };
+    void ResetOwes() { owesBank = 0; }
+};
+
+#endif

+ 109 - 0
CPPlusV6/Chapter 13/dma.cpp

@@ -0,0 +1,109 @@
+// dma.cpp --dma class methods
+
+#include "dma.h"
+#include <cstring>
+
+// baseDMA methods
+baseDMA::baseDMA(const char * l, int r)
+{
+    label = new char[std::strlen(l) + 1];
+    std::strcpy(label, l);
+    rating = r;
+}
+
+baseDMA::baseDMA(const baseDMA & rs)
+{
+    label = new char[std::strlen(rs.label) + 1];
+    std::strcpy(label, rs.label);
+    rating = rs.rating;
+}
+
+baseDMA::~baseDMA()
+{
+    delete [] label;
+}
+
+baseDMA & baseDMA::operator=(const baseDMA & rs)
+{
+    if (this == &rs)
+        return *this;
+    delete [] label;
+    label = new char[std::strlen(rs.label) + 1];
+    std::strcpy(label, rs.label);
+    rating = rs.rating;
+    return *this;
+}
+    
+std::ostream & operator<<(std::ostream & os, const baseDMA & rs)
+{
+    os << "Label: " << rs.label << std::endl;
+    os << "Rating: " << rs.rating << std::endl;
+    return os;
+}
+
+// lacksDMA methods
+lacksDMA::lacksDMA(const char * c, const char * l, int r)
+    : baseDMA(l, r)
+{
+    std::strncpy(color, c, 39);
+    color[39] = '\0';
+}
+
+lacksDMA::lacksDMA(const char * c, const baseDMA & rs)
+    : baseDMA(rs)
+{
+    std::strncpy(color, c, COL_LEN - 1);
+    color[COL_LEN - 1] = '\0';
+}
+
+std::ostream & operator<<(std::ostream & os, const lacksDMA & ls)
+{
+    os << (const baseDMA &) ls;
+    os << "Color: " << ls.color << std::endl;
+    return os;
+}
+
+// hasDMA methods
+hasDMA::hasDMA(const char * s, const char * l, int r)
+         : baseDMA(l, r)
+{
+    style = new char[std::strlen(s) + 1];
+    std::strcpy(style, s);
+}
+
+hasDMA::hasDMA(const char * s, const baseDMA & rs)
+         : baseDMA(rs)
+{
+    style = new char[std::strlen(s) + 1];
+    std::strcpy(style, s);
+}
+
+hasDMA::hasDMA(const hasDMA & hs)
+         : baseDMA(hs)  // invoke base class copy constructor
+{
+    style = new char[std::strlen(hs.style) + 1];
+    std::strcpy(style, hs.style);
+}
+
+hasDMA::~hasDMA()
+{
+    delete [] style;
+}
+
+hasDMA & hasDMA::operator=(const hasDMA & hs)
+{
+    if (this == &hs)
+        return *this;
+    baseDMA::operator=(hs);  // copy base portion
+    delete [] style;         // prepare for new style
+    style = new char[std::strlen(hs.style) + 1];
+    std::strcpy(style, hs.style);
+    return *this;
+}
+    
+std::ostream & operator<<(std::ostream & os, const hasDMA & hs)
+{
+    os << (const baseDMA &) hs;
+    os << "Style: " << hs.style << std::endl;
+    return os;
+}

+ 55 - 0
CPPlusV6/Chapter 13/dma.h

@@ -0,0 +1,55 @@
+// dma.h  -- inheritance and dynamic memory allocation
+#ifndef DMA_H_
+#define DMA_H_
+#include <iostream>
+
+//  Base Class Using DMA
+class baseDMA
+{
+private:
+    char * label;
+    int rating;
+    
+public:
+    baseDMA(const char * l = "null", int r = 0);
+    baseDMA(const baseDMA & rs);
+    virtual ~baseDMA();
+    baseDMA & operator=(const baseDMA & rs);
+    friend std::ostream & operator<<(std::ostream & os, 
+                                     const baseDMA & rs);
+};
+
+// derived class without DMA
+// no destructor needed
+// uses implicit copy constructor
+// uses implicit assignment operator
+class lacksDMA :public baseDMA
+{
+private:
+    enum { COL_LEN = 40};
+    char color[COL_LEN];
+public:
+    lacksDMA(const char * c = "blank", const char * l = "null",
+              int r = 0);
+    lacksDMA(const char * c, const baseDMA & rs);
+    friend std::ostream & operator<<(std::ostream & os, 
+                                     const lacksDMA & rs);
+};
+
+// derived class with DMA
+class hasDMA :public baseDMA
+{
+private:
+    char * style;
+public:
+    hasDMA(const char * s = "none", const char * l = "null",
+              int r = 0);
+    hasDMA(const char * s, const baseDMA & rs);
+    hasDMA(const hasDMA & hs);
+    ~hasDMA();
+    hasDMA & operator=(const hasDMA & rs);  
+    friend std::ostream & operator<<(std::ostream & os, 
+                                     const hasDMA & rs);
+};
+
+#endif

+ 12 - 0
CPPlusV6/Chapter 13/tabtenn0.cpp

@@ -0,0 +1,12 @@
+//tabtenn0.cpp -- simple base-class methods
+#include "tabtenn0.h"
+#include <iostream>
+
+TableTennisPlayer::TableTennisPlayer (const string & fn, 
+    const string & ln, bool ht) : firstname(fn),
+	    lastname(ln), hasTable(ht) {}
+    
+void TableTennisPlayer::Name() const
+{
+    std::cout << lastname << ", " << firstname;
+}

+ 20 - 0
CPPlusV6/Chapter 13/tabtenn0.h

@@ -0,0 +1,20 @@
+// tabtenn0.h -- a table-tennis base class
+#ifndef TABTENN0_H_
+#define TABTENN0_H_
+#include <string>
+using std::string;
+// simple base class
+class TableTennisPlayer
+{
+private:
+    string firstname;
+    string lastname;
+    bool hasTable;
+public:
+    TableTennisPlayer (const string & fn = "none",
+                       const string & ln = "none", bool ht = false);
+    void Name() const;
+    bool HasTable() const { return hasTable; };
+    void ResetTable(bool v) { hasTable = v; };
+};
+#endif

+ 24 - 0
CPPlusV6/Chapter 13/tabtenn1.cpp

@@ -0,0 +1,24 @@
+//tabtenn1.cpp -- simple base-class methods
+#include "tabtenn1.h"
+#include <iostream>
+
+TableTennisPlayer::TableTennisPlayer (const string & fn, 
+    const string & ln, bool ht) : firstname(fn),
+	    lastname(ln), hasTable(ht) {}
+    
+void TableTennisPlayer::Name() const
+{
+    std::cout << lastname << ", " << firstname;
+}
+
+// RatedPlayer methods
+RatedPlayer::RatedPlayer(unsigned int r, const string & fn,
+     const string & ln, bool ht) : TableTennisPlayer(fn, ln, ht)
+{
+    rating = r;
+}
+
+RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer & tp)
+    : TableTennisPlayer(tp), rating(r)
+{
+}

+ 34 - 0
CPPlusV6/Chapter 13/tabtenn1.h

@@ -0,0 +1,34 @@
+// tabtenn1.h -- a table-tennis base class
+#ifndef TABTENN1_H_
+#define TABTENN1_H_
+#include <string>
+using std::string;
+// simple base class
+class TableTennisPlayer
+{
+private:
+    string firstname;
+    string lastname;
+    bool hasTable;
+public:
+    TableTennisPlayer (const string & fn = "none",
+                       const string & ln = "none", bool ht = false);
+    void Name() const;
+    bool HasTable() const { return hasTable; };
+    void ResetTable(bool v) { hasTable = v; };
+};
+
+// simple derived class
+class RatedPlayer : public TableTennisPlayer
+{
+private:
+    unsigned int rating;
+public:
+    RatedPlayer (unsigned int r = 0, const string & fn = "none",
+                 const string & ln = "none", bool ht = false);
+    RatedPlayer(unsigned int r, const TableTennisPlayer & tp);
+    unsigned int Rating() const { return rating; }
+    void ResetRating (unsigned int r) {rating = r;}
+};
+
+#endif

+ 28 - 0
CPPlusV6/Chapter 13/usebrass1.cpp

@@ -0,0 +1,28 @@
+// usebrass1.cpp -- testing bank account classes
+// compile with brass.cpp
+#include <iostream>
+#include "brass.h"
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+
+    Brass Piggy("Porcelot Pigg", 381299, 4000.00);
+    BrassPlus Hoggy("Horatio Hogg", 382288, 3000.00);
+    Piggy.ViewAcct();
+    cout << endl;
+    Hoggy.ViewAcct();
+    cout << endl;
+    cout << "Depositing $1000 into the Hogg Account:\n";
+    Hoggy.Deposit(1000.00);
+    cout << "New balance: $" << Hoggy.Balance() << endl;
+    cout << "Withdrawing $4200 from the Pigg Account:\n";
+    Piggy.Withdraw(4200.00);
+    cout << "Pigg account balance: $" << Piggy.Balance() << endl;
+    cout << "Withdrawing $4200 from the Hogg Account:\n";
+    Hoggy.Withdraw(4200.00);
+    Hoggy.ViewAcct();
+	// std::cin.get();
+    return 0; 
+}

+ 67 - 0
CPPlusV6/Chapter 13/usebrass2.cpp

@@ -0,0 +1,67 @@
+// usebrass2.cpp -- polymorphic example
+// compile with brass.cpp
+#include <iostream>
+#include <string>
+#include "brass.h"
+const int CLIENTS = 4;
+
+int main()
+{
+   using std::cin;
+   using std::cout;
+   using std::endl;
+
+   Brass * p_clients[CLIENTS];
+   std::string temp;
+   long tempnum;
+   double tempbal;
+   char kind;
+
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       cout << "Enter client's name: ";
+       getline(cin,temp);
+       cout << "Enter client's account number: ";
+       cin >> tempnum;
+       cout << "Enter opening balance: $";
+       cin >> tempbal;
+       cout << "Enter 1 for Brass Account or "
+            << "2 for BrassPlus Account: ";
+       while (cin >> kind && (kind != '1' && kind != '2'))
+           cout <<"Enter either 1 or 2: ";
+       if (kind == '1')
+           p_clients[i] = new Brass(temp, tempnum, tempbal);
+       else
+       {
+           double tmax, trate;
+           cout << "Enter the overdraft limit: $";
+           cin >> tmax;
+           cout << "Enter the interest rate "
+                << "as a decimal fraction: ";
+           cin >> trate;
+           p_clients[i] = new BrassPlus(temp, tempnum, tempbal,
+                                        tmax, trate);
+        }
+        while (cin.get() != '\n')
+            continue;
+   }
+   cout << endl;
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       p_clients[i]->ViewAcct();
+       cout << endl;
+   }
+              
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       delete p_clients[i];  // free memory
+   }
+   cout << "Done.\n";         
+ /* code to keep window open 
+   if (!cin)
+      cin.clear();
+   while (cin.get() != '\n')
+      continue;
+*/
+   return 0; 
+}

+ 62 - 0
CPPlusV6/Chapter 13/usebrass3.cpp

@@ -0,0 +1,62 @@
+// usebrass3.cpp -- polymorphic example
+// compile with acctacb.cpp
+#include <iostream>
+#include <string>
+#include "acctabc.h"
+const int CLIENTS = 4;
+
+int main()
+{
+   using std::cin;
+   using std::cout;
+   using std::endl;
+
+   AcctABC * p_clients[CLIENTS];
+   std::string temp;
+   long tempnum;
+   double tempbal;
+   char kind;
+
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       cout << "Enter client's name: ";
+       getline(cin,temp);
+       cout << "Enter client's account number: ";
+       cin >> tempnum;
+       cout << "Enter opening balance: $";
+       cin >> tempbal;
+       cout << "Enter 1 for Brass Account or "
+            << "2 for BrassPlus Account: ";
+       while (cin >> kind && (kind != '1' && kind != '2'))
+           cout <<"Enter either 1 or 2: ";
+       if (kind == '1')
+           p_clients[i] = new Brass(temp, tempnum, tempbal);
+       else
+       {
+           double tmax, trate;
+           cout << "Enter the overdraft limit: $";
+           cin >> tmax;
+           cout << "Enter the interest rate "
+                << "as a decimal fraction: ";
+           cin >> trate;
+           p_clients[i] = new BrassPlus(temp, tempnum, tempbal,
+                                        tmax, trate);
+        }
+        while (cin.get() != '\n')
+            continue;
+   }
+   cout << endl;
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       p_clients[i]->ViewAcct();
+       cout << endl;
+   }
+              
+   for (int i = 0; i < CLIENTS; i++)
+   {
+       delete p_clients[i];  // free memory
+   }
+   cout << "Done.\n";    
+   // cin.get();
+   return 0; 
+}

+ 28 - 0
CPPlusV6/Chapter 13/usedma.cpp

@@ -0,0 +1,28 @@
+// usedma.cpp -- inheritance, friends, and DMA
+// compile with dma.cpp
+#include <iostream>
+#include "dma.h"
+int main()
+{
+    using std::cout;
+    using std::endl;
+
+    baseDMA shirt("Portabelly", 8);
+    lacksDMA balloon("red", "Blimpo", 4);
+    hasDMA map("Mercator", "Buffalo Keys", 5);
+    cout << "Displaying baseDMA object:\n";
+    cout << shirt << endl;
+    cout << "Displaying lacksDMA object:\n";
+    cout << balloon << endl;
+    cout << "Displaying hasDMA object:\n";
+    cout << map << endl;
+    lacksDMA balloon2(balloon);
+    cout << "Result of lacksDMA copy:\n";
+    cout << balloon2 << endl;
+    hasDMA map2;
+    map2 = map;
+    cout << "Result of hasDMA assignment:\n";
+    cout << map2 << endl;
+    // std::cin.get();
+    return 0; 
+}

+ 22 - 0
CPPlusV6/Chapter 13/usett0.cpp

@@ -0,0 +1,22 @@
+// usett0.cpp -- using a base class
+#include <iostream>
+#include "tabtenn0.h"
+
+int main ( void )
+{
+    using std::cout;
+    TableTennisPlayer player1("Chuck", "Blizzard", true);
+    TableTennisPlayer player2("Tara", "Boomdea", false);
+    player1.Name();
+    if (player1.HasTable())
+        cout << ": has a table.\n";
+    else
+        cout << ": hasn't a table.\n";
+    player2.Name();
+    if (player2.HasTable())
+        cout << ": has a table";
+    else
+        cout << ": hasn't a table.\n";
+    // std::cin.get();
+    return 0;
+}

+ 31 - 0
CPPlusV6/Chapter 13/usett1.cpp

@@ -0,0 +1,31 @@
+// usett1.cpp -- using base class and derived class
+#include <iostream>
+#include "tabtenn1.h"
+
+int main ( void )
+{
+    using std::cout;
+    using std::endl;
+    TableTennisPlayer player1("Tara", "Boomdea", false);
+    RatedPlayer rplayer1(1140, "Mallory", "Duck", true);
+    rplayer1.Name();          // derived object uses base method
+    if (rplayer1.HasTable())
+        cout << ": has a table.\n";
+    else
+        cout << ": hasn't a table.\n";
+    player1.Name();           // base object uses base method
+    if (player1.HasTable())
+        cout << ": has a table";
+    else
+        cout << ": hasn't a table.\n";
+    cout << "Name: ";
+    rplayer1.Name();
+    cout << "; Rating: " << rplayer1.Rating() << endl;
+// initialize RatedPlayer using TableTennisPlayer object
+    RatedPlayer rplayer2(1212, player1);
+    cout << "Name: ";
+    rplayer2.Name();
+    cout << "; Rating: " << rplayer2.Rating() << endl;
+    // std::cin.get();
+    return 0;
+}

+ 51 - 0
CPPlusV6/Chapter 14/arraytp.h

@@ -0,0 +1,51 @@
+//arraytp.h  -- Array Template
+#ifndef ARRAYTP_H_
+#define ARRAYTP_H_
+
+#include <iostream>
+#include <cstdlib>
+
+template <class T, int n>
+class ArrayTP
+{
+private:
+    T ar[n];
+public:
+    ArrayTP() {};
+    explicit ArrayTP(const T & v);
+    virtual T & operator[](int i);
+    virtual T operator[](int i) const;
+};
+
+template <class T, int n>
+ArrayTP<T,n>::ArrayTP(const T & v)
+{
+    for (int i = 0; i < n; i++)
+        ar[i] = v;
+}
+
+template <class T, int n>
+T & ArrayTP<T,n>::operator[](int i)
+{
+    if (i < 0 || i >= n)
+    {
+        std::cerr << "Error in array limits: " << i
+            << " is out of range\n";
+        std::exit(EXIT_FAILURE);
+    }
+    return ar[i];
+}
+
+template <class T, int n>
+T ArrayTP<T,n>::operator[](int i) const
+{
+    if (i < 0 || i >= n)
+    {
+        std::cerr << "Error in array limits: " << i
+            << " is out of range\n";
+        std::exit(EXIT_FAILURE);
+    }
+    return ar[i]; 
+}
+
+#endif

+ 60 - 0
CPPlusV6/Chapter 14/frnd2tmp.cpp

@@ -0,0 +1,60 @@
+// frnd2tmp.cpp -- template class with non-template friends
+#include <iostream>
+using std::cout;
+using std::endl;
+
+template <typename T>
+class HasFriend
+{
+private:
+    T item;
+    static int ct;
+public:
+    HasFriend(const T & i) : item(i) {ct++;}
+    ~HasFriend()  {ct--; }
+    friend void counts();
+    friend void reports(HasFriend<T> &); // template parameter
+};
+
+// each specialization has its own static data member
+template <typename T>
+int HasFriend<T>::ct = 0;
+
+// non-template friend to all HasFriend<T> classes
+void counts()
+{
+    cout << "int count: " << HasFriend<int>::ct << "; ";
+    cout << "double count: " << HasFriend<double>::ct << endl;
+}
+
+// non-template friend to the HasFriend<int> class
+void reports(HasFriend<int> & hf)
+{
+    cout <<"HasFriend<int>: " << hf.item << endl;
+}
+
+// non-template friend to the HasFriend<double> class
+void reports(HasFriend<double> & hf)
+{
+    cout <<"HasFriend<double>: " << hf.item << endl;
+}
+
+int main()
+{
+    cout << "No objects declared: ";
+    counts();
+    HasFriend<int> hfi1(10);
+    cout << "After hfi1 declared: ";
+    counts();
+    HasFriend<int> hfi2(20);
+    cout << "After hfi2 declared: ";
+    counts();
+    HasFriend<double> hfdb(10.5);
+    cout << "After hfdb declared: ";
+    counts(); 
+    reports(hfi1);
+    reports(hfi2);
+    reports(hfdb);
+    // std::cin.get();
+    return 0; 
+}

+ 32 - 0
CPPlusV6/Chapter 14/manyfrnd.cpp

@@ -0,0 +1,32 @@
+// manyfrnd.cpp -- unbound template friend to a template class
+#include <iostream>
+using std::cout;
+using std::endl;
+
+template <typename T>
+class ManyFriend
+{
+private:
+    T item;
+public:
+    ManyFriend(const T & i) : item(i) {}
+    template <typename C, typename D> friend void show2(C &, D &);
+};
+
+template <typename C, typename D> void show2(C & c, D & d)
+{
+    cout << c.item << ", " << d.item << endl;
+}
+
+int main()
+{
+    ManyFriend<int> hfi1(10);
+    ManyFriend<int> hfi2(20);
+    ManyFriend<double> hfdb(10.5);
+    cout << "hfi1, hfi2: ";
+    show2(hfi1, hfi2);
+    cout << "hfdb, hfi2: ";
+    show2(hfdb, hfi2);
+    // std::cin.get();
+    return 0;
+}

+ 55 - 0
CPPlusV6/Chapter 14/pairs.cpp

@@ -0,0 +1,55 @@
+// pairs.cpp -- defining and using a Pair template
+#include <iostream>
+#include <string>
+template <class T1, class T2>
+class Pair
+{
+private:
+    T1 a;
+    T2 b;
+public:
+    T1 & first();
+    T2 & second();
+    T1 first() const { return a; }
+    T2 second() const { return b; }
+    Pair(const T1 & aval, const T2 & bval) : a(aval), b(bval) { }
+    Pair() {}
+};
+
+template<class T1, class T2>
+T1 & Pair<T1,T2>::first()
+{
+    return a;
+}
+template<class T1, class T2>
+T2 & Pair<T1,T2>::second()
+{
+    return b;
+}
+
+int main()
+{
+    using std::cout;
+    using std::endl;
+    using std::string;
+    Pair<string, int> ratings[4] =
+    {
+        Pair<string, int>("The Purpled Duck", 5),
+        Pair<string, int>("Jaquie's Frisco Al Fresco", 4),
+        Pair<string, int>("Cafe Souffle", 5),
+        Pair<string, int>("Bertie's Eats", 3)
+    };
+
+    int joints = sizeof(ratings) / sizeof (Pair<string, int>);
+    cout << "Rating:\t Eatery\n";
+    for (int i = 0; i < joints; i++)
+        cout << ratings[i].second() << ":\t "
+             << ratings[i].first() << endl;
+    cout << "Oops! Revised rating:\n";
+    ratings[3].first() = "Bertie's Fab Eats";
+    ratings[3].second() = 6;
+    cout << ratings[3].second() << ":\t "
+         << ratings[3].first() << endl;
+   // std::cin.get();
+   return 0; 
+}

+ 51 - 0
CPPlusV6/Chapter 14/stacktem.cpp

@@ -0,0 +1,51 @@
+// stacktem.cpp -- testing the template stack class
+#include <iostream>
+#include <string>
+#include <cctype>
+#include "stacktp.h"
+using std::cin;
+using std::cout;
+
+int main()
+{
+    Stack<std::string> st;   // create an empty stack
+    char ch;
+    std::string po;
+    cout << "Please enter A to add a purchase order,\n"
+         << "P to process a PO, or Q to quit.\n";
+    while (cin >> ch && std::toupper(ch) != 'Q')
+    {
+        while (cin.get() != '\n')
+            continue;
+        if (!std::isalpha(ch))
+        {
+            cout << '\a';
+            continue;
+        }
+        switch(ch)
+        {
+            case 'A':
+            case 'a': cout << "Enter a PO number to add: ";
+                      cin >> po;
+                      if (st.isfull())
+                          cout << "stack already full\n";
+                      else
+                          st.push(po);
+                      break;
+            case 'P':
+            case 'p': if (st.isempty())
+                          cout << "stack already empty\n";
+                      else {
+                          st.pop(po);
+                          cout << "PO #" << po << " popped\n";
+                          break;
+                      }
+        }
+        cout << "Please enter A to add a purchase order,\n"
+             << "P to process a PO, or Q to quit.\n";
+    }
+    cout << "Bye\n";
+    // cin.get();
+    // cin.get();
+    return 0; 
+}

+ 61 - 0
CPPlusV6/Chapter 14/stacktp.h

@@ -0,0 +1,61 @@
+// stacktp.h -- a stack template
+#ifndef STACKTP_H_
+#define STACKTP_H_
+template <class Type>
+class Stack
+{
+private:
+    enum {MAX = 10};    // constant specific to class
+    Type items[MAX];    // holds stack items
+    int top;            // index for top stack item
+public:
+    Stack();
+    bool isempty();
+    bool isfull();
+    bool push(const Type & item); // add item to stack
+    bool pop(Type & item);        // pop top into item
+};
+
+template <class Type>
+Stack<Type>::Stack()
+{
+    top = 0;
+}
+
+template <class Type>
+bool Stack<Type>::isempty()
+{
+    return top == 0;
+}
+
+template <class Type>
+bool Stack<Type>::isfull()
+{
+    return top == MAX;
+}
+
+template <class Type>
+bool Stack<Type>::push(const Type & item)
+{
+    if (top < MAX)
+    {
+        items[top++] = item;
+        return true;
+    }
+    else
+        return false;
+}
+
+template <class Type>
+bool Stack<Type>::pop(Type & item)
+{
+    if (top > 0)
+    {
+        item = items[--top];
+        return true;
+    }
+    else
+        return false; 
+}
+
+#endif

+ 47 - 0
CPPlusV6/Chapter 14/stckoptr1.cpp

@@ -0,0 +1,47 @@
+// stkoptr1.cpp -- testing stack of pointers
+#include <iostream>
+#include <cstdlib>     // for rand(), srand()
+#include <ctime>       // for time()
+#include "stcktp1.h"
+const int Num = 10;
+int main()
+{
+    std::srand(std::time(0)); // randomize rand()
+    std::cout << "Please enter stack size: ";
+    int stacksize;
+    std::cin >> stacksize;
+// create an empty stack with stacksize slots
+    Stack<const char *> st(stacksize); 
+
+// in basket
+    const char * in[Num] = {
+            " 1: Hank Gilgamesh", " 2: Kiki Ishtar",
+            " 3: Betty Rocker", " 4: Ian Flagranti",
+            " 5: Wolfgang Kibble", " 6: Portia Koop",
+            " 7: Joy Almondo", " 8: Xaverie Paprika",
+            " 9: Juan Moore", "10: Misha Mache"
+            };
+ // out basket
+    const char * out[Num];
+
+    int processed = 0;
+    int nextin = 0;
+    while (processed < Num)
+    {
+        if (st.isempty())
+            st.push(in[nextin++]);
+        else if (st.isfull())
+            st.pop(out[processed++]);
+        else if (std::rand() % 2  && nextin < Num)   // 50-50 chance
+            st.push(in[nextin++]);
+        else
+            st.pop(out[processed++]);
+    }
+    for (int i = 0; i < Num; i++)
+        std::cout << out[i] << std::endl;
+
+    std::cout << "Bye\n";
+    // std::cin.get();
+    // std::cin.get();
+	return 0; 
+}

+ 78 - 0
CPPlusV6/Chapter 14/stcktp1.h

@@ -0,0 +1,78 @@
+// stcktp1.h -- modified Stack template
+#ifndef STCKTP1_H_
+#define STCKTP1_H_
+
+template <class Type>
+class Stack
+{
+private:
+    enum {SIZE = 10};    // default size
+    int stacksize;
+    Type * items;       // holds stack items
+    int top;            // index for top stack item
+public:
+    explicit Stack(int ss = SIZE);
+    Stack(const Stack & st);
+    ~Stack() { delete [] items; }
+    bool isempty() { return top == 0; }
+    bool isfull() { return top == stacksize; }
+    bool push(const Type & item);   // add item to stack
+    bool pop(Type & item);          // pop top into item
+    Stack & operator=(const Stack & st);
+};
+
+template <class Type>
+Stack<Type>::Stack(int ss) : stacksize(ss), top(0)
+{
+    items = new Type [stacksize];
+}
+
+template <class Type>
+Stack<Type>::Stack(const Stack & st)
+{
+    stacksize = st.stacksize;
+    top = st.top;
+    items = new Type [stacksize];
+    for (int i = 0; i < top; i++)
+        items[i] = st.items[i];
+}
+
+template <class Type>
+bool Stack<Type>::push(const Type & item)
+{
+    if (top < stacksize)
+    {
+        items[top++] = item;
+        return true;
+    }
+    else
+        return false;
+}
+
+template <class Type>
+bool Stack<Type>::pop(Type & item)
+{
+    if (top > 0)
+    {
+        item = items[--top];
+        return true;
+    }
+    else
+        return false;
+}
+
+template <class Type>
+Stack<Type> & Stack<Type>::operator=(const Stack<Type> & st)
+{
+    if (this == &st)
+        return *this;
+    delete [] items;
+    stacksize = st.stacksize;
+    top = st.top;
+    items = new Type [stacksize];
+    for (int i = 0; i < top; i++)
+        items[i] = st.items[i];
+    return *this; 
+}
+
+#endif

+ 75 - 0
CPPlusV6/Chapter 14/studentc.cpp

@@ -0,0 +1,75 @@
+// studentc.cpp -- Student class using containment
+#include "studentc.h"
+using std::ostream;
+using std::endl;
+using std::istream;
+using std::string;
+
+//public methods
+double Student::Average() const
+{
+    if (scores.size() > 0)
+        return scores.sum()/scores.size();  
+    else
+        return 0;
+}
+
+const string & Student::Name() const
+{
+    return name;
+}
+
+double & Student::operator[](int i)
+{
+    return scores[i];         // use valarray<double>::operator[]()
+}
+
+double Student::operator[](int i) const
+{
+    return scores[i];
+}
+
+// private method
+ostream & Student::arr_out(ostream & os) const
+{
+    int i;
+    int lim = scores.size();
+    if (lim > 0)
+    {
+        for (i = 0; i < lim; i++)
+        {
+            os << scores[i] << " ";
+            if (i % 5 == 4)
+                os << endl;
+        }
+        if (i % 5 != 0)
+            os << endl;
+    }
+    else
+        os << " empty array ";
+    return os; 
+}
+
+// friends
+
+// use string version of operator>>()
+istream & operator>>(istream & is, Student & stu)
+{
+    is >> stu.name;
+    return is; 
+}
+
+// use string friend getline(ostream &, const string &)
+istream & getline(istream & is, Student & stu)
+{
+    getline(is, stu.name);
+    return is;
+}
+
+// use string version of operator<<()
+ostream & operator<<(ostream & os, const Student & stu)
+{
+    os << "Scores for " << stu.name << ":\n";
+    stu.arr_out(os);  // use private method for scores
+    return os;
+}

+ 43 - 0
CPPlusV6/Chapter 14/studentc.h

@@ -0,0 +1,43 @@
+// studentc.h -- defining a Student class using containment
+#ifndef STUDENTC_H_
+#define STUDENTC_H_
+
+#include <iostream>
+#include <string>   
+#include <valarray>
+class Student
+{   
+private:
+    typedef std::valarray<double> ArrayDb;
+    std::string name;       // contained object
+    ArrayDb scores;         // contained object
+    // private method for scores output
+    std::ostream & arr_out(std::ostream & os) const;
+public:
+    Student() : name("Null Student"), scores() {}
+    explicit Student(const std::string & s)
+        : name(s), scores() {}
+    explicit Student(int n) : name("Nully"), scores(n) {}
+    Student(const std::string & s, int n)
+        : name(s), scores(n) {}
+    Student(const std::string & s, const ArrayDb & a)
+        : name(s), scores(a) {}
+    Student(const char * str, const double * pd, int n)
+        : name(str), scores(pd, n) {}
+    ~Student() {}
+    double Average() const;
+    const std::string & Name() const;
+    double & operator[](int i);
+    double operator[](int i) const;
+// friends
+    // input
+    friend std::istream & operator>>(std::istream & is,
+                                     Student & stu);  // 1 word
+    friend std::istream & getline(std::istream & is,
+                                  Student & stu);     // 1 line
+    // output
+    friend std::ostream & operator<<(std::ostream & os,
+                                     const Student & stu);
+};
+
+#endif

+ 74 - 0
CPPlusV6/Chapter 14/studenti.cpp

@@ -0,0 +1,74 @@
+// studenti.cpp -- Student class using private inheritance
+#include "studenti.h"
+using std::ostream;
+using std::endl;
+using std::istream;
+using std::string;
+
+// public methods
+double Student::Average() const
+{
+    if (ArrayDb::size() > 0)
+        return ArrayDb::sum()/ArrayDb::size();  
+    else
+        return 0;
+}
+
+const string & Student::Name() const
+{
+    return (const string &) *this;
+}
+
+double & Student::operator[](int i)
+{
+    return ArrayDb::operator[](i);         // use ArrayDb::operator[]()
+}
+
+double Student::operator[](int i) const
+{
+    return ArrayDb::operator[](i);
+}
+
+// private method
+ostream & Student::arr_out(ostream & os) const
+{
+    int i;
+    int lim = ArrayDb::size();
+    if (lim > 0)
+    {
+        for (i = 0; i < lim; i++)
+        {
+            os << ArrayDb::operator[](i) << " ";
+            if (i % 5 == 4)
+                os << endl;
+        }
+        if (i % 5 != 0)
+            os << endl;
+    }
+    else
+        os << " empty array ";
+    return os; 
+}
+
+// friends
+// use String version of operator>>()
+istream & operator>>(istream & is, Student & stu)
+{
+    is >> (string &)stu;
+    return is; 
+}
+
+// use string friend getline(ostream &, const string &)
+istream & getline(istream & is, Student & stu)
+{
+    getline(is, (string &)stu);
+    return is;
+}
+
+// use string version of operator<<()
+ostream & operator<<(ostream & os, const Student & stu)
+{
+    os << "Scores for " << (const string &) stu  << ":\n";
+    stu.arr_out(os);  // use private method for scores
+    return os;
+}

+ 41 - 0
CPPlusV6/Chapter 14/studenti.h

@@ -0,0 +1,41 @@
+// studenti.h -- defining a Student class using private inheritance
+#ifndef STUDENTC_H_
+#define STUDENTC_H_
+
+#include <iostream>
+#include <valarray>
+#include <string>   
+class Student : private std::string, private std::valarray<double>
+{   
+private:
+    typedef std::valarray<double> ArrayDb;
+    // private method for scores output
+    std::ostream & arr_out(std::ostream & os) const;
+public:
+    Student() : std::string("Null Student"), ArrayDb() {}
+    explicit Student(const std::string & s)
+            : std::string(s), ArrayDb() {}
+    explicit Student(int n) : std::string("Nully"), ArrayDb(n) {}
+    Student(const std::string & s, int n)
+            : std::string(s), ArrayDb(n) {}
+    Student(const std::string & s, const ArrayDb & a)
+            : std::string(s), ArrayDb(a) {}
+    Student(const char * str, const double * pd, int n)
+            : std::string(str), ArrayDb(pd, n) {}
+    ~Student() {}
+    double Average() const;
+    double & operator[](int i);
+    double operator[](int i) const;
+    const std::string & Name() const;
+// friends
+    // input
+    friend std::istream & operator>>(std::istream & is,
+                                     Student & stu);  // 1 word
+    friend std::istream & getline(std::istream & is,
+                                  Student & stu);     // 1 line
+    // output
+    friend std::ostream & operator<<(std::ostream & os,
+                                     const Student & stu);
+};
+
+#endif

+ 42 - 0
CPPlusV6/Chapter 14/tempmemb.cpp

@@ -0,0 +1,42 @@
+// tempmemb.cpp -- template members
+#include <iostream>
+using std::cout;
+using std::endl;
+
+template <typename T>
+class beta
+{
+private:
+    template <typename V>  // nested template class member
+    class hold
+    {
+    private:
+        V val;
+    public:
+        hold(V v  = 0) : val(v) {}
+        void show() const { cout << val << endl; }
+        V Value() const { return val; }
+    };
+    hold<T> q;             // template object
+    hold<int> n;           // template object
+public:
+    beta( T t, int i) : q(t), n(i) {}
+    template<typename U>   // template method
+    U blab(U u, T t) { return (n.Value() + q.Value()) * u / t; }
+    void Show() const { q.show(); n.show();}
+};
+
+int main()
+{
+    beta<double> guy(3.5, 3);
+    cout << "T was set to double\n";
+    guy.Show();
+    cout << "V was set to T, which is double, then V was set to int\n";
+    cout << guy.blab(10, 2.3) << endl;
+    cout << "U was set to int\n";
+    cout << guy.blab(10.0, 2.3) << endl;
+    cout << "U was set to double\n";
+    cout << "Done\n";
+    // std::cin.get();
+    return 0; 
+}

+ 40 - 0
CPPlusV6/Chapter 14/tempparm.cpp

@@ -0,0 +1,40 @@
+// tempparm.cpp – templates as parameters
+#include <iostream>
+#include "stacktp.h"
+
+template <template <typename T> class Thing>
+class Crab
+{
+private:
+    Thing<int> s1;
+    Thing<double> s2;
+public:
+    Crab() {};
+    // assumes the thing class has push() and pop() members
+    bool push(int a, double x) { return s1.push(a) && s2.push(x); }
+    bool pop(int & a, double & x){ return s1.pop(a) && s2.pop(x); }
+};
+    
+int main()
+{
+    using std::cout;
+    using std::cin;
+    using std::endl;
+    Crab<Stack> nebula;
+// Stack must match template <typename T> class thing   
+    int ni;
+    double nb;
+    cout << "Enter int double pairs, such as 4 3.5 (0 0 to end):\n";
+    while (cin>> ni >> nb && ni > 0 && nb > 0)
+    {
+        if (!nebula.push(ni, nb))
+            break;
+    }
+   
+    while (nebula.pop(ni, nb))
+           cout << ni << ", " << nb << endl;
+    cout << "Done.\n";
+    // cin.get();
+    // cin.get();
+    return 0; 
+}

+ 56 - 0
CPPlusV6/Chapter 14/tmp2tmp.cpp

@@ -0,0 +1,56 @@
+// tmp2tmp.cpp -- template friends to a template class
+#include <iostream>
+using std::cout;
+using std::endl;
+
+// template prototypes
+template <typename T> void counts();
+template <typename T> void report(T &);
+
+// template class
+template <typename TT>
+class HasFriendT
+{
+private:
+    TT item;
+    static int ct;
+public:
+    HasFriendT(const TT & i) : item(i) {ct++;}
+    ~HasFriendT() { ct--; }
+    friend void counts<TT>();
+    friend void report<>(HasFriendT<TT> &);
+};
+
+template <typename T>
+int HasFriendT<T>::ct = 0;
+
+// template friend functions definitions
+template <typename T>
+void counts()
+{
+    cout << "template size: " << sizeof(HasFriendT<T>) << "; ";
+    cout << "template counts(): " << HasFriendT<T>::ct << endl;
+}
+
+template <typename T>
+void report(T & hf)
+{
+    cout << hf.item << endl;
+}
+
+int main()
+{
+    counts<int>();
+    HasFriendT<int> hfi1(10);
+    HasFriendT<int> hfi2(20);
+    HasFriendT<double> hfdb(10.5);
+    report(hfi1);  // generate report(HasFriendT<int> &)
+    report(hfi2);  // generate report(HasFriendT<int> &)
+    report(hfdb);  // generate report(HasFriendT<double> &)
+    cout << "counts<int>() output:\n";
+    counts<int>();
+    cout << "counts<double>() output:\n";
+    counts<double>();
+    // std::cin.get();
+    return 0; 
+}

+ 40 - 0
CPPlusV6/Chapter 14/twod.cpp

@@ -0,0 +1,40 @@
+// twod.cpp -- making a 2-d array
+#include <iostream>
+#include "arraytp.h"
+int main(void)
+{
+    using std::cout;
+    using std::endl;
+    ArrayTP<int, 10> sums;
+    ArrayTP<double, 10> aves;
+    ArrayTP< ArrayTP<int,5>, 10> twodee;
+    
+    
+    int i, j;
+    
+    for (i = 0; i < 10; i++)
+    {
+        sums[i] = 0;
+        for (j = 0; j < 5; j++)
+        {
+            twodee[i][j] = (i + 1) * (j + 1);
+            sums[i] += twodee[i][j];
+        }
+        aves[i] = (double) sums[i] / 10;
+    }
+    for (i = 0; i < 10; i++)
+    {
+        for (j = 0; j < 5; j++)
+        {
+            cout.width(2);
+            cout << twodee[i][j] << ' ';
+        }
+        cout << ": sum = ";
+        cout.width(3);
+        cout  << sums[i] << ", average = " << aves[i] << endl;
+    }
+    
+    cout << "Done.\n";
+    // std::cin.get();
+    return 0;
+}

+ 46 - 0
CPPlusV6/Chapter 14/use_stuc.cpp

@@ -0,0 +1,46 @@
+// use_stuc.cpp -- using a composite class
+// compile with studentc.cpp
+#include <iostream>
+#include "studentc.h"
+using std::cin;
+using std::cout;
+using std::endl;
+
+void set(Student & sa, int n);
+
+const int pupils = 3;
+const int quizzes = 5;
+
+int main()
+{
+    Student ada[pupils] = 
+        {Student(quizzes), Student(quizzes), Student(quizzes)};
+
+    int i;
+    for (i = 0; i < pupils; ++i)
+        set(ada[i], quizzes);
+    cout << "\nStudent List:\n";
+    for (i = 0; i < pupils; ++i)
+        cout << ada[i].Name() << endl;
+    cout << "\nResults:";
+    for (i = 0; i < pupils; ++i)
+    {
+        cout << endl << ada[i];
+        cout << "average: " << ada[i].Average() << endl;
+    }
+    cout << "Done.\n";
+    // cin.get();
+
+    return 0;
+}
+
+void set(Student & sa, int n)
+{
+    cout << "Please enter the student's name: ";
+    getline(cin, sa);
+    cout << "Please enter " << n << " quiz scores:\n";
+    for (int i = 0; i < n; i++)
+        cin >> sa[i];
+    while (cin.get() != '\n')
+        continue; 
+}

+ 45 - 0
CPPlusV6/Chapter 14/use_stui.cpp

@@ -0,0 +1,45 @@
+// use_stui.cpp -- using a class with private inheritance
+// compile with studenti.cpp
+#include <iostream>
+#include "studenti.h"
+using std::cin;
+using std::cout;
+using std::endl;
+
+void set(Student & sa, int n);
+
+const int pupils = 3;
+const int quizzes = 5;
+
+int main()
+{
+    Student ada[pupils] = 
+        {Student(quizzes), Student(quizzes), Student(quizzes)};
+
+    int i;
+    for (i = 0; i < pupils; i++)
+        set(ada[i], quizzes);
+    cout << "\nStudent List:\n";
+    for (i = 0; i < pupils; ++i)
+        cout << ada[i].Name() << endl;
+    cout << "\nResults:";
+    for (i = 0; i < pupils; i++)
+    {
+        cout << endl << ada[i];
+        cout << "average: " << ada[i].Average() << endl;
+    }
+    cout << "Done.\n";
+    // cin.get();
+    return 0;
+}
+
+void set(Student & sa, int n)
+{
+    cout << "Please enter the student's name: ";
+    getline(cin, sa);
+    cout << "Please enter " << n << " quiz scores:\n";
+    for (int i = 0; i < n; i++)
+        cin >> sa[i];
+    while (cin.get() != '\n')
+        continue; 
+}

+ 74 - 0
CPPlusV6/Chapter 14/worker0.cpp

@@ -0,0 +1,74 @@
+// worker0.cpp -- working class methods
+#include "worker0.h"
+#include <iostream>
+using std::cout;
+using std::cin;
+using std::endl;
+// Worker methods
+
+// must implement virtual destructor, even if pure
+Worker::~Worker() {}
+
+void Worker::Set()
+{
+    cout << "Enter worker's name: ";
+    getline(cin, fullname);
+    cout << "Enter worker's ID: ";
+    cin >> id;
+    while (cin.get() != '\n')
+        continue;
+}
+
+void Worker::Show() const
+{
+    cout << "Name: " << fullname << "\n";
+    cout << "Employee ID: " << id << "\n";
+}
+
+// Waiter methods
+void Waiter::Set()
+{
+    Worker::Set();
+    cout << "Enter waiter's panache rating: ";
+    cin >> panache;
+    while (cin.get() != '\n')
+        continue;
+}
+
+void Waiter::Show() const
+{
+    cout << "Category: waiter\n";
+    Worker::Show();
+    cout << "Panache rating: " << panache << "\n";
+}
+
+// Singer methods
+
+char * Singer::pv[] = {"other", "alto", "contralto",
+            "soprano", "bass", "baritone", "tenor"};
+
+void Singer::Set()
+{
+    Worker::Set();
+    cout << "Enter number for singer's vocal range:\n";
+    int i;
+    for (i = 0; i < Vtypes; i++)
+    {
+        cout << i << ": " << pv[i] << "   ";
+        if ( i % 4 == 3)
+            cout << endl;
+    }
+    if (i % 4 != 0)
+        cout << endl;
+    while (cin >>  voice && (voice < 0 || voice >= Vtypes) )
+        cout << "Please enter a value >= 0 and < " << Vtypes << endl;
+    while (cin.get() != '\n')
+        continue;
+}
+
+void Singer::Show() const
+{
+    cout << "Category: singer\n";
+    Worker::Show();
+    cout << "Vocal range: " << pv[voice] << endl;
+}

+ 54 - 0
CPPlusV6/Chapter 14/worker0.h

@@ -0,0 +1,54 @@
+// worker0.h  -- working classes
+#ifndef WORKER0_H_
+#define WORKER0_H_
+
+#include <string>
+
+class Worker   // an abstract base class
+{
+private:
+    std::string fullname;
+    long id;
+public:
+    Worker() : fullname("no one"), id(0L) {}
+    Worker(const std::string & s, long n)
+            : fullname(s), id(n) {}
+    virtual ~Worker() = 0;   // pure virtual destructor
+    virtual void Set();
+    virtual void Show() const;
+};
+
+class Waiter : public Worker
+{
+private:
+    int panache;
+public:
+    Waiter() : Worker(), panache(0) {}
+    Waiter(const std::string & s, long n, int p = 0)
+            : Worker(s, n), panache(p) {}
+    Waiter(const Worker & wk, int p = 0)
+            : Worker(wk), panache(p) {}
+    void Set();
+    void Show() const;
+};
+
+class Singer : public Worker
+{
+protected:
+    enum {other, alto, contralto, soprano,
+                    bass, baritone, tenor};
+    enum {Vtypes = 7};
+private:
+    static char *pv[Vtypes];    // string equivs of voice types
+    int voice;
+public:
+    Singer() : Worker(), voice(other) {}
+    Singer(const std::string & s, long n, int v = other)
+            : Worker(s, n), voice(v) {}
+    Singer(const Worker & wk, int v = other)
+            : Worker(wk), voice(v) {}
+    void Set();
+    void Show() const;
+};
+
+#endif

+ 123 - 0
CPPlusV6/Chapter 14/workermi.cpp

@@ -0,0 +1,123 @@
+// workermi.cpp -- working class methods with MI
+#include "workermi.h"
+#include <iostream>
+using std::cout;
+using std::cin;
+using std::endl;
+// Worker methods
+Worker::~Worker() { }
+
+// protected methods
+void Worker::Data() const
+{
+    cout << "Name: " << fullname << endl;
+    cout << "Employee ID: " << id << endl;
+}
+
+void Worker::Get()
+{
+    getline(cin, fullname);
+    cout << "Enter worker's ID: ";
+    cin >> id;
+    while (cin.get() != '\n')
+        continue;
+}
+
+// Waiter methods
+void Waiter::Set()
+{
+    cout << "Enter waiter's name: ";
+    Worker::Get();
+    Get();
+}
+
+void Waiter::Show() const
+{
+    cout << "Category: waiter\n";
+    Worker::Data();
+    Data();
+}
+
+// protected methods
+void Waiter::Data() const
+{
+    cout << "Panache rating: " << panache << endl;
+}
+
+void Waiter::Get()
+{
+    cout << "Enter waiter's panache rating: ";
+    cin >> panache;
+    while (cin.get() != '\n')
+        continue;
+}
+
+// Singer methods
+
+char * Singer::pv[Singer::Vtypes] = {"other", "alto", "contralto",
+            "soprano", "bass", "baritone", "tenor"};
+
+void Singer::Set()
+{
+    cout << "Enter singer's name: ";
+    Worker::Get();
+    Get();
+}
+
+void Singer::Show() const
+{
+    cout << "Category: singer\n";
+    Worker::Data();
+    Data();
+}
+
+// protected methods
+void Singer::Data() const
+{
+    cout << "Vocal range: " << pv[voice] << endl;
+}
+
+void Singer::Get()
+{
+    cout << "Enter number for singer's vocal range:\n";
+    int i;
+    for (i = 0; i < Vtypes; i++)
+    {
+        cout << i << ": " << pv[i] << "   ";
+        if ( i % 4 == 3)
+            cout << endl;
+    }
+    if (i % 4 != 0)
+        cout << '\n';
+    while (cin >>  voice && (voice < 0 || voice >= Vtypes) )
+        cout << "Please enter a value >= 0 and < " << Vtypes << endl;
+    while (cin.get() != '\n')
+        continue;
+}
+
+// SingingWaiter methods
+void SingingWaiter::Data() const
+{
+    Singer::Data();
+    Waiter::Data();
+}
+
+void SingingWaiter::Get()
+{
+    Waiter::Get();
+    Singer::Get();
+}
+
+void SingingWaiter::Set()
+{
+    cout << "Enter singing waiter's name: ";
+    Worker::Get();
+    Get();
+}
+
+void SingingWaiter::Show() const
+{
+    cout << "Category: singing waiter\n";
+    Worker::Data();
+    Data();
+}

+ 83 - 0
CPPlusV6/Chapter 14/workermi.h

@@ -0,0 +1,83 @@
+// workermi.h  -- working classes with MI
+#ifndef WORKERMI_H_
+#define WORKERMI_H_
+
+#include <string>
+
+class Worker   // an abstract base class
+{
+private:
+    std::string fullname;
+    long id;
+protected:
+    virtual void Data() const;
+    virtual void Get();
+public:
+    Worker() : fullname("no one"), id(0L) {}
+    Worker(const std::string & s, long n)
+            : fullname(s), id(n) {}
+    virtual ~Worker() = 0; // pure virtual function
+    virtual void Set() = 0;
+    virtual void Show() const = 0;
+};
+
+class Waiter : virtual public Worker
+{
+private:
+    int panache;
+protected:
+    void Data() const;
+    void Get();
+public:
+    Waiter() : Worker(), panache(0) {}
+    Waiter(const std::string & s, long n, int p = 0)
+            : Worker(s, n), panache(p) {}
+    Waiter(const Worker & wk, int p = 0)
+            : Worker(wk), panache(p) {}
+    void Set();
+    void Show() const;
+};
+
+class Singer : virtual public Worker
+{
+protected:
+enum {other, alto, contralto, soprano,
+                    bass, baritone, tenor};
+    enum {Vtypes = 7};
+    void Data() const;
+    void Get();
+private:
+    static char *pv[Vtypes];    // string equivs of voice types
+    int voice;
+public:
+    Singer() : Worker(), voice(other) {}
+    Singer(const std::string & s, long n, int v = other)
+            : Worker(s, n), voice(v) {}
+    Singer(const Worker & wk, int v = other)
+            : Worker(wk), voice(v) {}
+    void Set();
+    void Show() const;
+};
+
+// multiple inheritance
+class SingingWaiter : public Singer, public Waiter
+{
+protected:
+    void Data() const;
+    void Get();
+public:
+    SingingWaiter()  {}
+    SingingWaiter(const std::string & s, long n, int p = 0,
+                            int v = other)
+            : Worker(s,n), Waiter(s, n, p), Singer(s, n, v) {}
+    SingingWaiter(const Worker & wk, int p = 0, int v = other)
+            : Worker(wk), Waiter(wk,p), Singer(wk,v) {}
+    SingingWaiter(const Waiter & wt, int v = other)
+            : Worker(wt),Waiter(wt), Singer(wt,v) {}
+    SingingWaiter(const Singer & wt, int p = 0)
+            : Worker(wt),Waiter(wt,p), Singer(wt) {}
+    void Set();
+    void Show() const; 
+};
+
+#endif

+ 58 - 0
CPPlusV6/Chapter 14/workmi.cpp

@@ -0,0 +1,58 @@
+// workmi.cpp -- multiple inheritance
+// compile with workermi.cpp
+#include <iostream>
+#include <cstring>
+#include "workermi.h"
+const int SIZE = 5;
+
+int main()
+{
+   using std::cin;
+   using std::cout;
+   using std::endl;
+   using std::strchr;
+
+   Worker * lolas[SIZE];
+
+    int ct;
+    for (ct = 0; ct < SIZE; ct++)
+    {
+        char choice;
+        cout << "Enter the employee category:\n"
+            << "w: waiter  s: singer  "
+            << "t: singing waiter  q: quit\n";
+        cin >> choice;
+        while (strchr("wstq", choice) == NULL)
+        {
+            cout << "Please enter a w, s, t, or q: ";
+            cin >> choice;
+        }
+        if (choice == 'q')
+            break;
+        switch(choice)
+        {
+            case 'w':   lolas[ct] = new Waiter;
+                        break;
+            case 's':   lolas[ct] = new Singer;
+                        break;
+            case 't':   lolas[ct] = new SingingWaiter;
+                        break;
+        }
+        cin.get();
+        lolas[ct]->Set();
+    }
+
+    cout << "\nHere is your staff:\n";
+    int i;
+    for (i = 0; i < ct; i++)
+    {
+        cout << endl;
+        lolas[i]->Show();
+    }
+    for (i = 0; i < ct; i++)
+        delete lolas[i];
+    cout << "Bye.\n";
+    // cin.get();
+    // cin.get();
+    return 0; 
+}

+ 24 - 0
CPPlusV6/Chapter 14/worktest.cpp

@@ -0,0 +1,24 @@
+// worktest.cpp -- test worker class hierarchy
+#include <iostream>
+#include "worker0.h"
+const int LIM = 4;
+int main()
+{
+    Waiter bob("Bob Apple", 314L, 5);
+    Singer bev("Beverly Hills", 522L, 3);
+    Waiter w_temp;
+    Singer s_temp;
+
+    Worker * pw[LIM] = {&bob, &bev, &w_temp, &s_temp};
+
+    int i;
+    for (i = 2; i < LIM; i++)
+        pw[i]->Set();
+    for (i = 0; i < LIM; i++)
+    {
+        pw[i]->Show();
+        std::cout << std::endl;
+    }
+    // std::cin.get();
+    return 0;
+}

+ 28 - 0
CPPlusV6/Chapter 15/constcast.cpp

@@ -0,0 +1,28 @@
+// constcast.cpp -- using const_cast<>
+#include <iostream>
+using std::cout;
+using std::endl;
+
+void change(const int * pt, int n);
+
+int main()
+{
+    int pop1 = 38383;
+    const int pop2 = 2000;
+
+    cout << "pop1, pop2: " << pop1 << ", " << pop2 << endl;
+    change(&pop1, -103);
+    change(&pop2, -103);
+    cout << "pop1, pop2: " << pop1 << ", " << pop2 << endl;
+    // std::cin.get();
+    return 0;
+}
+
+void change(const int * pt, int n)
+{
+    int * pc;
+  
+    pc = const_cast<int *>(pt);
+    *pc += n;
+ 
+}

+ 30 - 0
CPPlusV6/Chapter 15/error1.cpp

@@ -0,0 +1,30 @@
+//error1.cpp -- using the abort() function
+#include <iostream>
+#include <cstdlib>
+double hmean(double a, double b);
+
+int main()
+{
+    double x, y, z;
+
+    std::cout << "Enter two numbers: ";
+    while (std::cin >> x >> y)
+    {
+        z = hmean(x,y);
+        std::cout << "Harmonic mean of " << x << " and " << y
+            << " is " << z << std::endl;
+        std::cout << "Enter next set of numbers <q to quit>: ";
+    }
+    std::cout << "Bye!\n";
+    return 0;
+}
+
+double hmean(double a, double b)
+{
+    if (a == -b)
+    {
+        std::cout << "untenable arguments to hmean()\n";
+        std::abort();
+    }
+    return 2.0 * a * b / (a + b); 
+}

+ 38 - 0
CPPlusV6/Chapter 15/error2.cpp

@@ -0,0 +1,38 @@
+//error2.cpp -- returning an error code
+#include <iostream>
+#include <cfloat>  // (or float.h) for DBL_MAX
+
+bool hmean(double a, double b, double * ans);
+
+int main()
+{
+    double x, y, z;
+
+    std::cout << "Enter two numbers: ";
+    while (std::cin >> x >> y)
+    {
+        if (hmean(x,y,&z))
+            std::cout << "Harmonic mean of " << x << " and " << y
+                << " is " << z << std::endl;
+        else
+            std::cout << "One value should not be the negative "
+                << "of the other - try again.\n";
+        std::cout << "Enter next set of numbers <q to quit>: ";
+    }
+    std::cout << "Bye!\n";
+    return 0;
+}
+
+bool hmean(double a, double b, double * ans)
+{
+    if (a == -b)
+    {
+        *ans = DBL_MAX;
+        return false;
+    }
+    else
+    {
+        *ans = 2.0 * a * b / (a + b);
+        return true;
+    }
+}

+ 34 - 0
CPPlusV6/Chapter 15/error3.cpp

@@ -0,0 +1,34 @@
+// error3.cpp -- using an exception
+#include <iostream>
+double hmean(double a, double b);
+
+int main()
+{
+    double x, y, z;
+
+    std::cout << "Enter two numbers: ";
+    while (std::cin >> x >> y)
+    {
+        try {                   // start of try block
+            z = hmean(x,y);
+        }                       // end of try block
+        catch (const char * s)  // start of exception handler
+        {
+            std::cout << s << std::endl;
+            std::cout << "Enter a new pair of numbers: ";
+            continue;
+        }                       // end of handler
+        std::cout << "Harmonic mean of " << x << " and " << y
+            << " is " << z << std::endl;
+        std::cout << "Enter next set of numbers <q to quit>: ";
+    }
+    std::cout << "Bye!\n";
+    return 0;
+}
+
+double hmean(double a, double b)
+{
+    if (a == -b)
+        throw "bad hmean() arguments: a = -b not allowed";
+    return 2.0 * a * b / (a + b); 
+}

部分文件因为文件数量过多而无法显示