• C++ Primer Plus(第6版)中文版——课后练习程序代码


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

    9.6.1

    #ifndef _9.6.1_H_
    #define _9.6.1_H_
    
    #include <iostream>
    #include <cstring>
    
    const int Len = 40;
    struct golf
    {
        char fullname[Len];
        int handicap;
    };
    
    //non-interactive version
    //function sets golf structure to provided name, handicap
    //using values passed as arguments to the function
    void setgolf(golf & g, const char * name, int hc);
    
    //interactive version
    //function solicits name and handicap fron user
    //and sets the members of g to the values entered
    //return 1 if name is enterd, 0 if name is empty string
    int setgolf(golf & g);
    
    //function resets handicap to new value
    void handicap(golf & g, int hc);
    
    //function displays contents of golf structure
    void showgolf(const golf & g);
    
    #endif
    View Code
    #include "9.6.1.h"
    
    void setgolf(golf & g, const char * name, int hc)
    {
        memcpy(g.fullname, name, Len);
        g.handicap = hc;
    }
    
    int setgolf(golf & g)
    {
        char str[Len] = "";
        int hc = 0;
        
        std::cout << "Enter the name : ";
        std::cin.getline(str,Len);    //会接受空格、回车、TAB等空字符串 
        
        if(str[0] == '')
        {
            return 0;
        }
        std::cout << "Enter the handicap : ";
        std::cin >> hc;
        std::cin.get();    //接收掉上一次输入丢下的回车字符 
        
        setgolf(g, str, hc);
        
        return 1;
    }
    
    void handicap(golf & g, int hc)
    {
        g.handicap = hc;
    }
    
    void showgolf(const golf & g)
    {
        std::cout << "Name : " << g.fullname << std::endl;
        std::cout << "Handicap : " << g.handicap << std::endl << std::endl;
    }
    View Code
    #include "9.6.1.h"
    
    int main(void)
    {
        golf g[10];
        
        for(int i = 0; i < 10; i++)
        {
            if(setgolf(g[i]) == 0)
            {
                std::cout << "End input!" << std::endl;
                break;
            }
            showgolf(g[i]);
        }
        if(g[0].fullname[0] != '')
        {
            handicap(g[0], 10086);
            showgolf(g[0]);
        }
        
        return 0;
    }
    View Code

    9.6.2

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

    9.6.3

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

    9.6.4

    #ifndef _9.6.4_H_
    #define _9.6.4_H_
    
    #include <iostream>
    #include <algorithm>
    
    namespace SALES
    {
        const int QUARTERS = 4;
        struct Sales
        {
            double sales[QUARTERS];
            double average;
            double max;
            double min;
        };
        //copies the lesser of 4 or n items from the array ar
        //to the sales member of s and computes and stores the
        //average, maximum, and minimum values of the enterd items;
        //remaining elements of sales, if any, set to 0
        void setSales(Sales & s, const double ar[], int n);
        
        //gathers sales for 4 quarters interactively, stores them
        //in the sales member of s and computes and stores the
        //average, maximum, and minimum values
        void setSales(Sales & s);
        
        //display all information in structure s
        void showSales(const Sales & s);
    }
    
    #endif
    View Code
    #include "9.6.4.h"
    
    namespace SALES
    {
        void setSales(Sales & s, const double ar[], int n)
        {
            double sum = 0.0;
            
            for(int i = 0; i < n; i++)
            {
                s.sales[i] = ar[i];
                sum += ar[i];
            }
            for(int i = n; i < QUARTERS; i++)
            {
                s.sales[i] = 0;
            }
            s.average = sum / n;
            
            //STL求最大值算法,返回的是指针- - 
            s.max = *std::max_element(s.sales, s.sales + n);
            s.min = *std::min_element(s.sales, s.sales + n);
        }
            
        void setSales(Sales & s)
        {
            double sum = 0.0;
            
            std::cout << "Input the " << QUARTERS << " number" << std::endl;
            
            for(int i = 0; i < QUARTERS; i++)
            {
                std::cin >> s.sales[i];
                sum += s.sales[i];
            }
            s.average = sum / QUARTERS;
            
            //STL求最大值算法,返回的是指针- - 
            s.max = *std::max_element(s.sales, s.sales + QUARTERS);
            s.min = *std::min_element(s.sales, s.sales + QUARTERS);
        }
            
        void showSales(const Sales & s)
        {
            std::cout << "Sales : ";
            for(int i = 0; i < QUARTERS; i++)
            {
                std::cout << s.sales[i] << " ";
            }
            
            std::cout << std::endl << "Average : " << s.average << std::endl;
            std::cout <<  "Max : " << s.max << std::endl;
            std::cout <<  "Min : " << s.min << std::endl;
        }
    }
    View Code
    #include "9.6.4.h"
    
    int main(void)
    {
        SALES::Sales a, b;
        
        SALES::setSales(a);
        SALES::showSales(a);
        std::cout << std::endl;
        
        double ar[] = {1.23, 3.5, 6, 1};
        SALES::setSales(b, ar, 4);
        SALES::showSales(b);
        
        return 0;
    }
    View Code

    10.10.1

    #ifndef _10.10.1_H_
    #define _10.10.1_H_
    
    #include <iostream>
    #include <string>
    
    class BankAccount
    {
        private:
            std::string name;
            std::string acctnum;
            double balance;
        
        public:
            BankAccount(const std::string & client, const std::string & num, double bal = 0.0);
            void show(void) const;
            void deposit(double cash);
            void withdraw(double cash);
    };
    
    #endif
    View Code
    #include "10.10.1.h"
    
    BankAccount::BankAccount(const std::string & client, const std::string & num, double bal)
    {
        name = client;
        acctnum = num;
        balance = bal;
    }
    
    void BankAccount::show(void) const
    {
        std::cout << "Name : " << name << std::endl;
        std::cout << "Acctnum : " << acctnum << std::endl;
        
        //Store original flags
        std::streamsize prec = std::cout.precision(2);
        std::ios_base::fmtflags orig = std::cout.setf(std::ios_base::fixed);
        
        std::cout << "Money : " << balance << std::endl << std::endl;;
        
        //Reset to stored values
        std::cout.setf(orig, std::ios_base::floatfield);
        std::cout.precision(prec);
    }
    
    void BankAccount::deposit(double cash)
    {
        if(cash <= 0)
        {
            std::cerr << "Error : money must >0!" << std::endl;
        }
        else
        {
            balance += cash;
        }
    }
    
    void BankAccount::withdraw(double cash)
    {
        if(cash <= 0)
        {
            std::cerr << "Error : money must >0!" << std::endl;
        }
        else if(balance - cash < 0)
        {
            std::cerr << "Error : you can only take out : " << balance << "$" << std::endl;
        }
        else
        {
            balance -= cash;
        }
    }
    View Code
    #include "10.10.1.h"
    
    int main(void)
    {
        BankAccount pingge("PingGe", "10086", 99999999);
        
        pingge.show();
            
        pingge.deposit(1);
        pingge.show();
        
        pingge.deposit(-1);
        pingge.show();
        
        pingge.withdraw(99999999);
        pingge.show();
        
        pingge.withdraw(2);
        pingge.show();
        
        return 0;
    }
    View Code

    10.10.2

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

    10.10.3

    #ifndef _10.10.3_H_
    #define _10.10.3_H_
    
    #include <string>
    #include <cstring>
    #include <iostream>
    
    class golf
    {
        private:
            std::string fullname;
            int handicap_;
            
        public:
            golf();
    
            
            golf(const std::string & name, int hc);
            
            ~golf();
            
            void handicap(int hc);
            
            void showgolf(void) const;
    };
    
    #endif
    View Code
    #include "10.10.3.h"
    
    golf::golf()
    {
        std::cout << "Enter the name : ";
        std::cin >> this->fullname;
        
        std::cout << "Enter the handicap : ";
        std::cin >> this->handicap_; 
    }
            
    golf::golf(const std::string & name, int hc)
    {
        fullname = name;
        handicap_ = hc;
    }
    
    golf::~golf()
    {
        std::cout << "Call ~golf" << std::endl;
    }
        
    void golf::handicap(int hc)
    {
        handicap_ = hc;
    }
            
    void golf::showgolf(void) const
    {
        std::cout << "Name : " << fullname << std::endl;
        std::cout << "Handicap : " << handicap_ << std::endl;
    }
    View Code
    #include "10.10.3.h"
    
    int main(void)
    {
        (golf()).showgolf();
        
        golf p = golf("pingge", 10086);
        p.showgolf();
        
        golf q;
        q.showgolf();
        
        golf r("fuck", 110);
        r.showgolf();
        return 0;
    }
    View Code

    10.10.4

    #ifndef _10.10.4_H_
    #define _10.10.4_H_
    
    #include <iostream>
    #include <algorithm>
    
    namespace SALES
    {
        class Sales
        {
            private:
                //enum{QUARTERS = 4};
                static const int QUARTERS = 4;
                double sales[QUARTERS],
                         average,
                         max,
                         min;
                
            public:
                //copies the lesser of 4 or n items from the array ar
                //to the sales member of s and computes and stores the
                //average, maximum, and minimum values of the enterd items;
                //remaining elements of sales, if any, set to 0
                Sales(const double ar[], int n);
                
                //gathers sales for 4 quarters interactively, stores them
                //in the sales member of s and computes and stores the
                //average, maximum, and minimum values
                Sales();
                
                //display all information in structure s
                void showSales(void) const;
        };
    }
    
    #endif
    View Code
    #include "10.10.4.h"
    
    namespace SALES
    {
        Sales::Sales()
        {
            std::cout << "Input the " << QUARTERS << " number" << std::endl;
            
            double sum = 0.0;
            
            for(int i = 0; i < QUARTERS; i++)
            {
                std::cin >> sales[i];
                sum += sales[i];
            }
            average = sum / QUARTERS;
            
            //STL求最大值算法,返回的是指针- - 
            max = *std::max_element(sales, sales + QUARTERS);
            min = *std::min_element(sales, sales + QUARTERS);
        }
        
        Sales::Sales(const double ar[], int n)
        {
            double sum = 0.0;
            
            for(int i = 0; i < n; i++)
            {
                sales[i] = ar[i];
                sum += ar[i];
            }
            for(int i = n; i < QUARTERS; i++)
            {
                sales[i] = 0;
            }
            average = sum / n;
            
            //STL求最大值算法,返回的是指针- - 
            max = *std::max_element(sales, sales + n);
            min = *std::min_element(sales, sales + n);
        }
        
        void Sales::showSales(void) const
        {
            std::cout << "Sales : ";
            for(int i = 0; i < QUARTERS; i++)
            {
                std::cout << sales[i] << " ";
            }
            
            std::cout << std::endl << "Average : " << average << std::endl;
            std::cout <<  "Max : " << max << std::endl;
            std::cout <<  "Min : " << min << std::endl;
        }
    }
    View Code
    #include "10.10.4.h"
    
    int main(void)
    {
        SALES::Sales a;
        a.showSales();
        
        double ar[] = {1.23, 3.5, 6, 1};
        SALES::Sales b(ar, 4);
        b.showSales();
        
        return 0;
    }
    View Code

    10.10.5

    #ifndef _10.10.5_H_
    #define _10.10.5_H_
    
    struct customer
    {
        char fullname[35];
        double payment;
    };
    
    typedef customer 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;
    
            //add item to stack
            //push() returns false if stack already is full, true otherwise
            bool push(const Item & item);
    
            //pop top into item
            //pop() returns false if stack already is empty, true otherwise
            bool pop(Item & item);
    };
    
    #endif
    View Code
    #include "10.10.5.h"
    
    Stack::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;
        }
    }
    View Code
    #include <iostream>
    #include "10.10.5.h"
    
    int main(void)
    {
        Item a{"pingge", 10086};
        Item b;
    
        Stack st;
    
        while(st.push(a) == true);
    
        while(st.pop(b) == true )
        {
            std::cout << b.fullname << b.payment << std::endl;
        }
        return 0;
    }
    View Code

    10.10.6

    #ifndef _10.10.6_H_
    #define _10.10.6_H_
    
    #include <iostream>
    
    class Move
    {
        private:
            double x;
            double y;
    
        public:
            Move(double a = 0, double b = 0);   //Sets x, y to a, b
            void showmove(void) const;          //Shows current x, y values
    
            //This function adds x of m to x of invoking object to get new x,
            //adds y of m to y of invoking object to get new y, creates a new
            //move object initialized to new x, y values and returns it
            Move add(const Move & m) const;
    
            void reset(double a = 0, double b = 0);  //Resets x, y to a, b
    };
    
    #endif
    View Code
    #include "10.10.6.h"
    
    Move::Move(double a, double b)
    {
        x = a;
        y = b;
    }
    
    void Move::showmove(void) const
    {
        std::cout << "X : " << x << std::endl;
        std::cout << "Y : " << y << std::endl;
    }
    
    Move Move::add(const Move & m) const
    {
        Move new_object = Move(x + m.x, y + m.y);
        return new_object;
    }
    
    void Move::reset(double a, double b)
    {
        x = a;
        y = b;
    }
    View Code
    #include "10.10.6.h"
    
    int main()
    {
        Move a(1.23, 4.56);
        a.showmove();
    
        (a.add(Move(1, 1))).showmove();
    
        a.reset();
        a.showmove();
        return 0;
    }
    View Code

    10.10.8

    #ifndef _10.10.7_H_
    #define _10.10.7_H_
    
    #include <iostream>
    #include <string>
    
    struct node
    {
        std::string name;
        int money;
    };
    
    typedef node Item;
    
    class List
    {
        private:
            struct NODE
            {
                Item data;
                struct NODE * last;
                struct NODE * next;
            };
            NODE *head, *p;
    
            unsigned long Length;
    
        public:
            List();
            ~List();
            void Add(const Item & item);
            unsigned long Size(void) const;
            void Clear(void);
            bool Empty(void) const;
            Item & Front(void) const;
            Item & Back(void) const;
            void Visit(void(*pf)(Item &));
    };
    
    #endif
    View Code
    #include "10.10.8.h"
    
    List::List()
    {
        head = new NODE;
    
        head->last = head->next = head;
    
        p = NULL;
    
        Length = 0;
    }
    
    List::~List()
    {
        NODE *q = NULL;
        for(p = head->next; p->next != head; p = q)
        {
            q = p->next;
            delete p;
        }
        delete head;
    }
    
    void List::Add(const Item & item)
    {
        p = new NODE;
        p->data = item;
    
        p->last = head->last;
        p->last->next = p;
        p->next = head;
        head->last = p;
    
        Length++;
    }
    
    unsigned long List::Size(void) const
    {
        return Length;
    }
    
    void List::Clear(void)
    {
        NODE *q = NULL;
        for(p = head->next; p != head; p = q)
        {
            q = p->next;
            delete p;
        }
    
        head->last = head->next = head;
    
        p = NULL;
    
        Length = 0;
    }
    
    bool List::Empty(void) const
    {
        if(head->next == head)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    Item & List::Front(void) const
    {
        return head->next->data;
    }
    
    Item & List::Back(void) const
    {
        return head->last->data;
    }
    
    void List::Visit(void (*pf)(Item &))
    {
        for(p = head->next; p != head; p = p->next)
        {
            (*pf)(p->data);
        }
    }
    View Code
    #include "10.10.8.h"
    
    void Show(const Item & item)
    {
        std::cout << "Name : " << item.name << std::endl;
        std::cout << "Money : " << item.money << std::endl << std::endl;
    }
    
    void Operate(Item & item)
    {
        item.money += 10;
    }
    
    int main()
    {
        Item a{"PingGe", 10086},
             b{"Ass", -1};
    
    
        List list;
        std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
        std::cout << "List length : " << list.Size() << std::endl;
    
        //1add
        std::cout << std::endl << "Begin Add" << std::endl;;
        list.Add(a);
        std::cout << "Front of the list : " << std::endl;   Show(list.Front());
        std::cout << "Back of the list : " << std::endl;    Show(list.Back());
        std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
        std::cout << "List length : " << list.Size() << std::endl;
    
        //2add
        std::cout << std::endl << "Next Add" << std::endl;;
        list.Add(b);
        std::cout << "Front of the list : " << std::endl;   Show(list.Front());
        std::cout << "Back of the list : " << std::endl;    Show(list.Back());
        std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
        std::cout << "List length : " << list.Size() << std::endl;
    
        //3operate +10
        std::cout << std::endl << "Call operate" << std::endl;;
        list.Visit(&Operate);
        std::cout << "Front of the list : " << std::endl;   Show(list.Front());
        std::cout << "Back of the list : " << std::endl;    Show(list.Back());
        std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
        std::cout << "List length : " << list.Size() << std::endl;
    
        //4clear
        std::cout << std::endl << "Call clear" << std::endl;;
        list.Clear();
        //std::cout << "Front of the list : " << std::endl;   Show(list.Front());
        //std::cout << "Back of the list : " << std::endl;    Show(list.Back());
        std::cout << (list.Empty() ? "List is empty!" : "List isn't empty!") << std::endl;
        std::cout << "List length : " << list.Size() << std::endl;
    
        return 0;
    }
    View Code

    11.9.1

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

    11.9.5

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

    11.9.6

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

    11.9.7

    #ifndef _11.9.7_H_
    #define _11.9.7_H_
    
    #include <iostream>
    
    class Complex
    {
        private:
            double a, b;
    
        public:
            Complex();
            Complex(double a_, double b_);
    
            //operator overloading
            Complex operator+(const Complex & c) const;
            Complex operator-(const Complex & c) const;
            Complex operator*(const Complex & c) const;
            Complex operator~(void) const;
    
            //firends
            friend Complex operator*(const Complex & c, double x);
    
            friend Complex operator*(double x, const Complex & c);
            friend std::ostream & operator<<(std::ostream & os, const Complex & c);
            friend std::istream & operator>>(std::istream & is, Complex & c);
    };
    
    #endif
    View Code
    #include "11.9.7.h"
    
    Complex::Complex()
    {
        a = b = 0.0;
    }
    
    Complex::Complex(double a_, double b_)
    {
        a = a_;
        b = b_;
    }
    
    Complex Complex::operator+(const Complex & c) const
    {
        return Complex(a + c.a, b + c.b);
    }
    
    Complex Complex::operator-(const Complex & c) const
    {
        return Complex(a - c.a, b - c.b);
    }
    Complex Complex::operator*(const Complex & c) const
    {
        return Complex(a * c.a - b * c.b, a * c.b + b * c.a);
    }
    
    Complex Complex::operator~(void) const
    {
        return Complex(a, -b);
    }
    
    Complex operator*(const Complex & c, double x)
    {
        return Complex(x * c.a, x * c.b);
    }
    
    Complex operator*(double x, const Complex & c)
    {
        return Complex(x * c.a, x * c.b);
    }
    
    std::ostream & operator<<(std::ostream & os, const Complex & c)
    {
        os << "(" << c.a << ", " << c.b << "i)";
        return os;
    }
    
    std::istream & operator>>(std::istream & is, Complex & c)
    {
        std::cout << "real : ";
        is >> c.a;
        std::cout << "imaginary : ";
        is >> c.b;
    
        return is;
    }
    View Code
    #include "11.9.7.h"
    using namespace std;
    
    int main(void)
    {
        Complex a(3.0, 4.0);
        Complex c;
        cout << "Enter a complex number (q to quit) : " << endl;
        while(cin >> c)
        {
            cout << "c is " << c << endl;
            cout << "complex conjugate is " << ~c << endl;
            cout << "a is " << a << endl;
    
            cout << "a + c is " << a + c << endl;
            cout << "a - c is " << a - c << endl;
            cout << "a * c is " << a * c << endl;
            cout << "2 * c is " << 2 * c << endl;
            cout << "Enter a complex number (q to quit) : " << endl;
        }
        cout << "Done!" << endl;
    
        return 0;
    }
    View Code

    12.10.1

    #ifndef _COW_H_
    #define _COW_H_
    
    class Cow
    {
    private:
        char name[20];
        char * hobby;
        double weight;
    
    public:
        Cow();
        Cow(const char * nm, const char * ho, double wt);
        Cow(const Cow & c);
        ~Cow();
        Cow & operator=(const Cow & c);
        void ShowCow(void) const;   //display all cow data
    };
    
    #endif
    View Code
    #include "12.10.1.h"
    #include <iostream>
    #include <cstring>
    
    Cow::Cow()
    {
        name[0] = '';
        //hobby = NULL;
        hobby = new char[1];
        hobby[0] = '';
        weight = 0;
    }
    
    Cow::Cow(const char * nm, const char * ho, double wt)
    {
        strcpy(name, nm);
        hobby = new char[strlen(ho) + 1];
        strcpy(hobby, ho);
        weight = wt;
    }
    
    Cow::Cow(const Cow & c)
    {
        strcpy(name, c.name);
        hobby = new char[strlen(c.hobby) + 1];
        strcpy(hobby, c.hobby);
        weight = c.weight;
    }
    
    Cow::~Cow()
    {
        std::cout << "Call ~Cow!" << std::endl;
        delete [] hobby;
    }
    
    Cow & Cow::operator=(const Cow & c)
    {
        if(this == &c)
        {
            return *this;
        }
    
        strcpy(name, c.name);
        delete [] hobby;
        hobby = new char[strlen(c.hobby) + 1];
        strcpy(hobby, c.hobby);
        weight = c.weight;
    
        return *this;
    }
    
    void Cow::ShowCow(void) const
    {
        std::cout << "Name : " << name << std::endl;
        std::cout << "Hobby : " << hobby << " : " << &hobby << std::endl;
        std::cout << "Weight : " << weight << std::endl;
    }
    View Code
    #include "12.10.1.h"
    
    int main(void)
    {
        {
            Cow c1;
            Cow c2("PingGe", "Watch TV", 120);
            Cow c3(c2);
            Cow c4 = c3;
    
            c1.ShowCow();
    
            c2.ShowCow();
            c3.ShowCow();
            c4.ShowCow();
        }
        return 0;
    }
    View Code

    12.10.2

    #ifndef _12.10.2_H_
    #define _12.10.2_H_
    
    #include <iostream>
    
    class String
    {
        private:
            char * str;                     //pointer to string
            int len;                        //length of string
            static int num_strings;         //number of objects
            static const int CINLIM = 80;   //cin input limit
    
        public:
            //constructors and other methods
            String(const char * s);         //constructor
            String();                       //default constructor
            String(const String & st);      //copy constructor
            ~String();                      //destructor
            int length(void) const  {return len;}
    
            //overloaded operator methods
            String & operator=(const String & st);
            String & operator=(const char * s);
            char & operator[](int i);
            const char & operator[](int i) const;
    
            //overloaded operator friends
            friend bool operator<(const String & st1, const String & st2);
            friend bool operator>(const String & st1, const String & st2);
            friend bool operator==(const String & st1, const String & st2);
            friend std::ostream & operator<<(std::ostream & os, const String & st);
            friend std::istream & operator>>(std::istream & is, String & st);
    
            //new methods
            friend String operator+(const String & st1, const String & st2);
            void Stringlow(void);
            void Stringup(void);
            int has(const char & ch) const;
    
            //static function
            static int HowMany(void);
    };
    
    #endif
    View Code
    #include <cstring>
    #include <cctype>
    #include "12.10.2.h"
    
    //initializing static class member
    int String::num_strings = 0;
    
    //static method
    int String::HowMany(void)
    {
        return num_strings;
    }
    
    //class methods
    String::String(const char * s)
    {
        len = std::strlen(s);
        str = new char[len + 1];
        std::strcpy(str, s);
        num_strings++;
    }
    
    String::String()
    {
        len = 0;
        str = new char[1];
        str[0] = '';
        num_strings++;
    }
    
    String::String(const String & st)
    {
        num_strings++;
        len = st.len;
        str = new char[len + 1];
        std::strcpy(str, st.str);
    }
    
    String::~String()
    {
        --num_strings;
        delete [] str;
    }
    
    //overloaded operator methods
    //assign a String to a string
    String & String::operator=(const String & st)
    {
        if(this == &st)
        {
            return *this;
        }
        delete [] str;
        len = st.len;
        str = new char[len + 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];
    }
    
    
    //overliaded 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_iterator_tag
    std::ostream & operator<<(std::ostream & os, const String & st)
    {
        os << st.str;
        return os;
    }
    
    std::istream & operator>>(std::istream & is, String & st)
    {
        char temp[String::CINLIM];
        is.get(temp, String::CINLIM);
        if(is)
        {
            st = temp;
        }
        while(is && is.get() != '
    ');
    
        return is;
    }
    
    
    String operator+(const String & st1, const String & st2)
    {
        char * s = new char[st1.len + st2.len + 1];
        strcpy(s, st1.str);
        strcat(s, st2.str);
    
        String add(s);
        delete [] s;
    
        return add;
    }
    
    void String::Stringlow(void)
    {
        for(int i = 0; i < len; i++)
        {
            str[i] = std::tolower(str[i]);
        }
    }
    
    void String::Stringup(void)
    {
        for(int i = 0; i < len; i++)
        {
            str[i] = std::toupper(str[i]);
        }
    }
    
    int String::has(const char & ch) const
    {
        int n = 0;
        for(int i = 0; i < len; i++)
        {
            if(str[i] == ch)
            {
                n++;
            }
        }
        return n;
    }
    View Code
    #include <iostream>
    #include "12.10.2.h"
    using namespace std;
    
    int main(void)
    {
        String s1(" and I am a C++ student.");
        String s2 = "Please enter your name : ";
        String s3;
        cout << s2;
        cin >> s3;
        s2 = "My name is " + s3;
    
        cout << s2 << ".
    ";
        s2 = s2 + s1;
        s2.Stringup();
        cout << "The string
    " << s2 << "
    contains " << s2.has('A') << " 'A' characters in it.
    ";
        s1 = "red";
    
        String rgb[3] = {String(s1), String("green"), String("blue")};
        cout << "Enter the name of a primary color for mixing light : ";
        String ans;
        bool success = false;
    
        while(cin >> ans)
        {
            ans.Stringlow();
            for(int i = 0; i < 3; i++)
            {
                if(ans == rgb[i])
                {
                    cout << "That's right!
    ";
                    success = true;
                    break;
                }
            }
            if(success)
            {
                break;
            }
            else
            {
                cout << "Try again!
    ";
            }
        }
        cout << "Bye!
    ";
    
        return 0;
    }
    View Code

    12.10.3

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

    12.10.4

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

    12.10.6

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

    13.11.1

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

    13.11.2

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

    13.11.3

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

    13.11.4

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

    15.8.1

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

    15.8.2

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

    15.8.3

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


    15.8.4

    #include <stdexcept>
    #include <string>
    
    class Sales
    {
    public:
        enum {MONTHS = 12}; // could be a static const
        class bad_index : public std::logic_error
        {
        private:
            int bi; // bad index value
        public:
            explicit bad_index(int ix, const std::string & s = "Index error in Sales object
    ");
            virtual ~bad_index() throw() {}
            int bi_val() const {return bi;}
        };
    
        explicit Sales(int yy = 0);
        Sales(int yy, const double * gr, int n);
        virtual ~Sales() {}
    
        int Year() const {return year;}
        virtual double operator[](int i) const;
        virtual double & operator[](int i);
    
    private:
        double gross[MONTHS];
        int year;
    };
    
    class LabeledSales : public Sales
    {
    public:
        class nbad_index : public Sales::bad_index
        {
        private:
            std::string lbl;
        public:
            nbad_index(const std::string & lb, int ix, const std::string & s = "Index error in LabeledSales object
    ");
            const std::string & label_val() const {return lbl;}
            virtual ~nbad_index() throw() {}
        };
    
        explicit LabeledSales(const std::string & lb = "none", int yy = 0);
        LabeledSales(const std::string & lb, int yy, const double * gr, int n);
        virtual ~LabeledSales() {}
    
        const std::string & Label() const {return label;}
        virtual double operator[](int i) const;
        virtual double & operator[](int i);
    
    private:
        std::string label;
    };
    View Code
    #include "15.8.4.h"
    using std::string;
    
    Sales::bad_index::bad_index(int ix, const string & s) : std::logic_error(s), bi(ix)
    {
    
    }
    
    Sales::Sales(int yy)
    {
        year = yy;
        for(int i = 0; i < MONTHS; i++)
        {
            gross[i] = 0;
        }
    }
    
    Sales::Sales(int yy, const double * gr, int n)
    {
        year = yy;
        int lim = (n < MONTHS) ? n : MONTHS;
        int i;
        for(i = 0; i < lim; i++)
        {
            gross[i] = gr[i];
        }
        for(; i < MONTHS; i++)
        {
            gross[i] = 0;
        }
    }
    
    double Sales::operator[](int i) const
    {
        if(i < 0 || i >= MONTHS)
        {
            throw bad_index(i);
        }
        return gross[i];
    }
    
    double & Sales::operator[](int i)
    {
        if(i < 0 || i >= MONTHS)
        {
            throw bad_index(i);
        }
        return gross[i];
    }
    
    LabeledSales::nbad_index::nbad_index(const string & lb, int ix, const string & s) : Sales::bad_index(ix, s)
    {
        lbl = lb;
    }
    
    LabeledSales::LabeledSales(const string & lb, int yy) : Sales(yy)
    {
        label = lb;
    }
    
    LabeledSales::LabeledSales(const string & lb, int yy, const double * gr, int n) : Sales(yy, gr, n)
    {
        label = lb;
    }
    
    double LabeledSales::operator[](int i) const
    {
        if(i < 0 || i >= MONTHS)
        {
            throw nbad_index(Label(), i);
        }
        return Sales::operator[](i);
    }
    
    double & LabeledSales::operator[](int i)
    {
        if(i < 0 || i >= MONTHS)
        {
            throw nbad_index(Label(), i);
        }
        return Sales::operator[](i);
    }
    View Code
    #include <iostream>
    #include <typeinfo>
    #include "15.8.4.h"
    using namespace std;
    
    int main()
    {
        double vals1[12] = {1220, 1100, 1122, 2212, 1232, 2334,
                            2884, 2393, 3302, 2922, 3002, 3544};
        double vals2[12] = {12, 11, 22, 21, 32, 34,
                            28, 29, 33, 29, 32, 35};
        Sales sales1(2011, vals1, 12);
        LabeledSales sales2("Blogstar", 2012, vals2, 12);
    
        cout << "First try block:
    ";
        try
        {
            cout << "Year = " << sales1.Year() << endl;
            for(int i = 0; i < 12; i++)
            {
                cout << sales1[i] << ' ';
                if(i % 6 == 5)
                {
                    cout << endl;
                }
            }
            cout << "Year = " << sales2.Year() << endl;
            cout << "Label = " << sales2.Label() << endl;
    
            for(int i = 0; i <= 12; i++)
            {
                cout << sales2[i] << ' ';
                if(i % 6 == 5)
                {
                    cout << endl;
                }
            }
            cout << "End of try block 1.
    ";
        }
        catch(Sales::bad_index & bad)
        {
            cout << bad.what();
            if(typeid(LabeledSales::nbad_index) == typeid(bad))
            {
                LabeledSales::nbad_index * nbad = static_cast<LabeledSales::nbad_index *>(&bad);
                cout << "Company: " << nbad->label_val() << endl;
            }
            cout << "bad index: " << bad.bi_val() << endl;
        }
    
        cout << "
    Next try block:
    ";
        try
        {
            sales2[2] = 37.5;
            sales1[20] = 23345;
            cout << "End of try block 2.
    ";
        }
        catch(Sales::bad_index & bad)
        {
            cout << bad.what();
            if(LabeledSales::nbad_index * nbad = dynamic_cast<LabeledSales::nbad_index *>(&bad))
            {
                cout << "Company: " << nbad->label_val() << endl;
            }
            cout << "bad index: " << bad.bi_val() << endl;
        }
        cout << "done
    ";
    
        return 0;
    }
    View Code

    17.8.1

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


    17.8.2

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


    17.8.3

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


    17.8.4

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


    17.8.5

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


    17.8.7

    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <algorithm>
    #include <vector>
    #include <string>
    using namespace std;
    
    void ShowStr(const string & s)
    {
        cout << s << endl;
    }
    
    class Store
    {
    public:
        Store(ofstream & fout_) : fout(fout_) {}
        void operator()(const string & s)
        {
            len = s.length();
            fout.write((char *)&len, sizeof(size_t));
            fout.write((char *)s.c_str(), len);
        }
    private:
        ofstream & fout;
        size_t len;
    };
    
    void GetStrs(ifstream & fin, vector<string> & vistr)
    {
        while(!fin.eof())
        {
            size_t len = 0;
            fin.read((char *)&len, sizeof(size_t));
            char ch;
            string s;
            for(size_t i = 0; i < len; i++)
            {
                fin.read((char *)&ch, sizeof(char));
                s.push_back(ch);
            }
            vistr.push_back(s);
        }
    }
    
    int main()
    {
        vector<string> vostr;
        string temp;
    
        //acquire strings
        cout << "Enter strings (empty line to quit): 
    ";
        while(getline(cin, temp) && temp[0] != '')
        {
            vostr.push_back(temp);
        }
        cout << "Here is your input. 
    ";
        for_each(vostr.begin(), vostr.end(), ShowStr);
    
        //store in a file
        ofstream fout("strings.dat", ios_base::out | ios_base::binary);
        for_each(vostr.begin(), vostr.end(), Store(fout));
        fout.close();
    
        //recover file contents
        vector<string> vistr;
        ifstream fin("strings.dat", ios_base::in | ios_base::binary);
        if(!fin.is_open())
        {
            cerr << "Could not open file for input.
    ";
            exit(EXIT_FAILURE);
        }
        GetStrs(fin, vistr);
        cout << "
    Here are the strings read from the file: 
    ";
        for_each(vistr.begin(), vistr.end(), ShowStr);
    
        return 0;
    }
    View Code
  • 相关阅读:
    asp.net pager
    asp.net 2.0
    mul page
    基于 Ajax 的持久对象映射(reship)
    asp.net run
    reship HttpProc
    some questions
    rss feed
    javascript function
    ioc
  • 原文地址:https://www.cnblogs.com/pingge/p/3414450.html
Copyright © 2020-2023  润新知