C.Primer.Plus(第六版)第14章 编程练习

来源:互联网 发布:天正建筑软件最新版 编辑:程序博客网 时间:2024/05/19 20:45

//14_1

#ifndef WINEC__H__#define WINEC__H__#include <iostream>#include <string>#include <valarray>#include <utility>class Wine{private:    std::string name;    std::pair<std::valarray<int>,std::valarray<int>> parameter;    int yearNum;public:    typedef std::valarray<int> ArrayInt;    typedef std::pair<ArrayInt,ArrayInt> PairArray;    Wine(const char* l,int y,const int yr[],const int bot[]);    Wine(const char* l,int y);    Wine(){}    void GetBottles();    const std::string & Label() const;    int sum() const;    void Show();};#endif
//wine.cpp#include "wine.h"Wine::Wine(const char* l,int y,const int yr[],const int bot[]){    name = l;     yearNum = y;    ArrayInt years(y);    ArrayInt bots(y);    for (int i = 0; i < y; ++i)      {          years[i] = yr[i];          bots[i] = bot[i];      }      parameter = std::make_pair(years, bots);    }Wine::Wine(const char* l,int y){    name = l ;    yearNum = y;    ArrayInt years(y);    ArrayInt bots(y);    parameter = std::make_pair(years, bots);}void Wine::GetBottles(){    std::cout << "Enter " << name << " data for " << yearNum << " year(s):\n";      parameter.first.resize(yearNum);      parameter.second.resize(yearNum);      for (int i = 0; i < yearNum; ++i)      {          std::cout << "Enter year: ";          std::cin >> parameter.first[i];          std::cout << "Enter bottles for that year: ";          std::cin >> parameter.second[i];      }  }const std::string & Wine::Label() const{    return name;}int Wine::sum() const{    return parameter.second.sum();  }void Wine::Show(){    std::cout << "Wine: " << name << std::endl;      std::cout << "\t\t" << "Year" << "\t" << "Bottles" << std::endl;      for (int i = 0; i < (int)parameter.first.size(); ++i)          std::cout << "\t\t" << parameter.first[i] << "\t" << parameter.second[i] << std::endl;  }
//main.cpp  #include <iostream>  #include "wine.h"  int main()  {      using std::cin;      using std::cout;      using std::endl;      cout << "Enter name of wine: ";      char lab[50];      cin.getline(lab, 50);      cout << "Enter number of years: ";      int yrs;      cin >> yrs;      Wine holding(lab, yrs);      holding.GetBottles();      holding.Show();      const int YRS = 3;      int y[YRS] = { 1993, 1995, 1998 };      int b[YRS] = { 48, 60, 72 };      Wine more("Gushing Grape Red", YRS, y, b);      more.Show();      cout << "Total bottles for " << more.Label() << ": " << more.sum() << endl;      cout << "Bye\n";      return 0;  }  

//14_2

#ifndef WINEC__H__#define WINEC__H__#include <iostream>#include <string>#include <valarray>#include <utility>class Wine : private std::string , private std::pair<std::valarray<int>,std::valarray<int>>{private:    int yearNum;public:    typedef std::valarray<int> ArrayInt;    typedef std::pair<ArrayInt,ArrayInt> PairArray;    Wine(const char* l,int y,const int yr[],const int bot[]);    Wine(const char* l,int y);    Wine(){}    void GetBottles();    const std::string & Label() const;    int sum() const;    void Show() const;};#endif
//wine.cpp#include "wine.h"Wine::Wine(const char* l,int y,const int yr[],const int bot[]):std::string(l),PairArray(ArrayInt(yr,y),ArrayInt(yr,y)),yearNum(y){}Wine::Wine(const char* l,int y):std::string(l),PairArray(ArrayInt(y),ArrayInt(y)),yearNum(y){}void Wine::GetBottles(){    std::cout << "Enter " << (const std::string &)(*this) << " data for " << yearNum << " year(s):\n";      PairArray & parameter = (PairArray &)(*this);      parameter.first.resize(yearNum);    parameter.second.resize(yearNum);      for (int i = 0; i < yearNum; ++i)      {          std::cout << "Enter year: ";          std::cin >> parameter.first[i];          std::cout << "Enter bottles for that year: ";          std::cin >> parameter.second[i];      }  }const std::string & Wine::Label() const{    return (const std::string &)(*this);}int Wine::sum() const{    return ((PairArray&)(*this)).second.sum();  }void Wine::Show() const{    std::cout << "Wine: " << (const std::string &)(*this) << std::endl;      std::cout << "\t\t" << "Year" << "\t" << "Bottles" << std::endl;      for (int i = 0; i < (int)((PairArray&)(*this)).first.size(); i++)          std::cout << "\t\t" << ((PairArray&)(*this)).first[i] << "\t" <<((PairArray&)(*this)).second[i] << std::endl;  }
//main.cpp  #include <iostream>  #include "wine.h"  int main()  {      using std::cin;      using std::cout;      using std::endl;      cout << "Enter name of wine: ";      char lab[50];      cin.getline(lab, 50);      cout << "Enter number of years: ";      int yrs;      cin >> yrs;      Wine holding(lab, yrs);      holding.GetBottles();      holding.Show();      const int YRS = 3;      int y[YRS] = { 1993, 1995, 1998 };      int b[YRS] = { 48, 60, 72 };      Wine more("Gushing Grape Red", YRS, y, b);      more.Show();      cout << "Total bottles for " << more.Label() << ": " << more.sum() << endl;      cout << "Bye\n";      return 0;  }  

//14_3

//QueueTp.h  #ifndef QUEUETP_H_  #define QUEUETP_H_  template <class T>  class QueueTp  {  private:      const static int LEN = 10;      T *data;      int top;  public:      QueueTp() { top = 0; data = new T[LEN]; }      QueueTp(int len) { top = 0; data = new T[2 * len]; }      ~QueueTp() { delete[] data; }      bool Push(T item);      bool Pop();      T &front() const;      T &rear() const;      bool isFull() const { return top == LEN; }      bool isEmpty() const { return top == 0; }  };  template <class T>  bool QueueTp<T>::Push(T item)  {      if (isFull())          return false;      for (int i = top; i > 0; --i)          data[i] = data[i - 1];      data[0] = item;      ++top;      return true;  }  template <class T>  bool QueueTp<T>::Pop()  {      if (isEmpty())          return false;      --top;      return true;  }  template <class T>  T &QueueTp<T>::front() const  {      return data[top - 1];  }  template <class T>  T &QueueTp<T>::rear() const  {      return data[0];  }  #endif  
//Workermi.h  #ifndef WORKERMI_H_  #define WORKERMI_H_  #include <string>  class Worker  {  private:      std::string fullname;      long id;  protected:      virtual void Data() const;      virtual void Get();  public:      Worker() : fullname("no one"), id(0L) {}      Worker(const std::string &s, long n) :fullname(s), id(n) {}      virtual ~Worker() = 0;      virtual void Set() = 0;      virtual void Show() const = 0;  };  class Waiter : virtual public Worker  {  private:      int panache;  protected:      void Data() const;      void Get();  public:      Waiter() : Worker(), panache(0) {}      Waiter(const std::string &s, long n, int p = 0) : Worker(s, n), panache(p) {}      Waiter(const Worker &wk, int p = 0) : Worker(wk), panache(p) {}      void Set();      void Show() const;  };  class Singer : virtual public Worker  {  protected:      enum { other, alto, contralto, soprano, bass, baritone, tenor };      enum { Vtypes = 7 };      void Data() const;      void Get();  private:      static char *pv[Vtypes];      int voice;  public:      Singer() : Worker(), voice(other) {}      Singer(const std::string &s, long n, int v = other) : Worker(s, n), voice(v) {}      Singer(const Worker &wk, int v = other) : Worker(wk), voice(v) {}      void Set();      void Show() const;  };  class SingingWaiter : public Singer, public Waiter  {  protected:      void Data() const;      void Get();  public:      SingingWaiter() {}      SingingWaiter(const std::string &s, long n, int p = 0, int v = other) : Worker(s, n), Waiter(s, n, p), Singer(s, n, v) {}      SingingWaiter(const Worker &wk, int p = 0, int v = other) : Worker(wk), Waiter(wk, p), Singer(wk, v) {}      SingingWaiter(const Waiter &wt, int v = other) : Worker(wt), Waiter(wt), Singer(wt, v) {}      SingingWaiter(const Singer &wt, int p = 0) : Worker(wt), Waiter(wt, p), Singer(wt) {}      void Set();      void Show() const;  };  #endif  
//Workermi.cpp  #include "worker.h"  #include <iostream>  using std::cout;  using std::cin;  using std::endl;  Worker::~Worker() {}  void Worker::Data() const  {      cout << "Name: " << fullname << endl;      cout << "Emplyee ID: " << id << endl;  }  void Worker::Get()  {      getline(cin, fullname);      cout << "Enter worker's ID: ";      cin >> id;      while (cin.get() != '\n')          continue;  }  void Waiter::Set()  {      cout << "Enter waiter's name: ";      Worker::Get();      Get();  }  void Waiter::Show() const  {      cout << "Category: waiter\n";      Worker::Data();      Data();  }  void Waiter::Data() const  {      cout << "Panache rating: " << panache << endl;  }  void Waiter::Get()  {      cout << "Enter waiter's panache rating: ";      cin >> panache;      while (cin.get() != '\n')          continue;  }  char *Singer::pv[Singer::Vtypes] = { "other", "alto", "contralto", "soprano", "bass", "baritone", "tenor" };  void Singer::Set()  {      cout << "Enter singer's name: ";      Worker::Get();      Get();  }  void Singer::Show() const  {      cout << "Category: singer\n";      Worker::Data();      Data();  }  void Singer::Data() const  {      cout << "Vocal range: " << pv[voice] << endl;  }  void Singer::Get()  {      cout << "Enter number for singer's vocal range:\n";      int i;      for (i = 0; i < Vtypes; ++i)      {          cout << i << ": " << pv[i] << "   ";          if (i % 4 == 3)              cout << endl;      }      if (i % 4 != 0)          cout << '\n';      cin >> voice;      while (cin.get() != '\n')          continue;  }  void SingingWaiter :: Data() const  {      Singer::Data();      Waiter::Data();  }  void SingingWaiter::Get()  {      Waiter::Get();      Singer::Get();  }  void SingingWaiter::Set()  {      cout << "Enter singing waiter's name: ";      Worker::Get();      Get();  }  void SingingWaiter::Show() const  {      cout << "Category: singing waiter\n";      Worker::Data();      Data();  }  
//workmi.cpp  #include <iostream>  #include <cstring>  #include "worker.h"  #include "queuetp.h"  const int SIZE = 5;  int main()  {      using std::cin;      using std::cout;      using std::endl;      using std::strchr;      QueueTp<Worker *> lolas(SIZE);      int ct;      for (ct = 0; ct < SIZE; ++ct)      {          char choice;          cout << "Enter the employee category: \n"              << "w: waiter s: singer "              << "t: singing waiter q: quiter\n";          cin >> choice;          while (strchr("wstq", choice) == NULL)          {              cout << "Please enter a w, s, t, or q: ";              cin >> choice;          }          if (choice == 'q')              break;          switch (choice)          {          case 'w': lolas.Push(new Waiter);              break;          case 's': lolas.Push(new Singer);              break;          case 't': lolas.Push(new SingingWaiter);              break;          }          cin.get();          lolas.rear()->Set();      }      cout << "\nHere is your staff:\n";      int i;      for (i = 0; i < ct; ++i)      {          cout << endl;          lolas.front()->Show();          lolas.Push(lolas.front());          lolas.Pop();      }      for (i = 0; i < ct; ++i)      {          delete lolas.front();          lolas.Pop();      }      cout << "Bye";      return 0;  }  
//14_4//person.h  #ifndef PERSON_H_  #define PERSON_H_  #include <iostream>  #include <string>  class Person  {  private:      std::string name;  protected:      const std::string &GetName() const { return name; }  public:      Person() { name = "NULL"; }      Person(const std::string &s) { name = s; }      Person(const char         *s) { name = s; }      virtual ~Person() {}      virtual void Show() const { std::cout << "Person" << std::endl; std::cout << "name: " << name << std::endl; }  };  class Gunslinger : virtual public Person  {  private:      int nick;      double DrawTime;  protected:      int GetNick() const { return nick; }  public:      Gunslinger() : Person() { nick = 0; DrawTime = 0; }      Gunslinger(const std::string &s, int n, double d) : Person(s) { nick = n; DrawTime = d; }      Gunslinger(const char *s, int n, double d) : Person(s) { nick = n; DrawTime = d; }      double Draw() const { return DrawTime; }      virtual void Show() const      {          std::cout << "Gunslinger" << std::endl;          std::cout << "name: " << GetName() << std::endl;          std::cout << "nick: " << nick << std::endl;          std::cout << "DrawTime: " << DrawTime << std::endl;      }  };  class PokerPlayer : virtual public Person  {  public:      PokerPlayer() : Person() {}      PokerPlayer(const std::string &s) : Person(s) {}      PokerPlayer(const char *s) : Person(s) {}      int Draw() const { return std::rand() % 52 + 1; }  };  class BadDude : public Gunslinger, public PokerPlayer  {  public:      BadDude() : Person(), Gunslinger(), PokerPlayer() {}      BadDude(const std::string &s) : Person(s) {}      BadDude(const char *s) : Person(s) {}      BadDude(const std::string &s, int n, double d) : Person(s), Gunslinger(s, n, d) {}      BadDude(const char *s, int n, double d) : Person(s), Gunslinger(s, n, d) {}      double Gdraw() const { return Gunslinger::Draw(); }      int Cdraw() const { return PokerPlayer::Draw(); }      virtual void Show() const      {          std::cout << "BadDude" << std::endl;          std::cout << "name: " << GetName() << std::endl;          std::cout << "nick: " << GetNick() << std::endl;          std::cout << "DrawTime: " <<  Gdraw() << std::endl;          std::cout << "Card: " << Cdraw() << std::endl;      }  };  #endif  
//main.cpp  #include "Person.h"  int main()  {      Person p("Tree");      Gunslinger g("Tree", 3, 1.2);      PokerPlayer po("shana");      BadDude b("yuuji", 2, 1.1);      Person *ptr = &p;      ptr->Show();      ptr = &g;      ptr->Show();      ptr = &po;      ptr->Show();      ptr = &b;      ptr->Show();      return 0;  }  
//14_5//emp.h  #ifndef EMP_H_  #define EMP_H_  #include <iostream>  #include <string>  class abstr_emp  {  private:      std::string fname;      std::string lname;      std::string job;  protected:      const std::string &GetFname() const{ return fname; }      const std::string &GetLname() const { return lname; }      const std::string &GetJob() const { return job; }      void SetFname() { std::cout << "Input Fname: "; std::getline(std::cin, fname); }      void SetLname() { std::cout << "Input Lname: "; std::getline(std::cin, lname); }      void SetJob() { std::cout << "Input Job: "; std::getline(std::cin, job); }  public:      abstr_emp();      abstr_emp(const std::string &fn, const std::string &ln, const std::string &j);      abstr_emp(const abstr_emp &e);      virtual void ShowAll() const;      virtual void SetAll();      friend std::ostream &operator<<(std::ostream &os, const abstr_emp &e);      virtual ~abstr_emp() = 0;  };  class employee : public abstr_emp  {  public:      employee();      employee(const std::string &fn, const std::string &ln, const std::string &j);      ~employee() {}      virtual void ShowAll() const;      virtual void SetAll();  };  class manager : virtual public abstr_emp  {  private:      int inchargeof;  protected:      int InChargeOf() const { return inchargeof; }      int &InChargOf() { return inchargeof; }      void SetInChargeOf() { std::cout << "Input InChargeOf: "; std::cin >> inchargeof; std::cin.get(); }  public:      manager();      manager(const std::string &fn, const std::string &ln, const std::string &j, int ico = 0);      manager(const abstr_emp &e, int ico);      manager(const manager &m);      ~manager() {}      virtual void ShowAll() const;      virtual void SetAll();  };  class fink : virtual public abstr_emp  {  private:      std::string reportsto;  protected:      const std::string ReportsTo() const { return reportsto; }      std::string &ReportsTo() { return reportsto; }      void SetReportsto() { std::cout << "Input reportsto: "; std::getline(std::cin, reportsto); }  public:      fink();      fink(const std::string &fn, const std::string &ln, const std::string &j, const std::string &rpo);      fink(const abstr_emp &e, const std::string &rpo);      fink(const fink &e);      ~fink() {}      virtual void ShowAll() const;      virtual void SetAll();  };  class highfink : public manager, public fink  {  public:      highfink();      highfink(const std::string &fn, const std::string &ln, const std::string &j, const std::string &rpo, int ico);      highfink(const abstr_emp &e, const std::string &rpo, int ico);      highfink(const fink &f, int ico);      highfink(const manager &m, const std::string &rpo);      highfink(const highfink &h);      ~highfink() {}      virtual void ShowAll() const;      virtual void SetAll();  };  #endif  
//emp.cpp  #include "emp.h"  abstr_emp::abstr_emp() : fname("NULL"), lname("NULL"), job("NULL")  {  }  abstr_emp::abstr_emp(const std::string & fn, const std::string & ln, const std::string & j) : fname(fn), lname(ln), job(j)  {  }  abstr_emp::abstr_emp(const abstr_emp & e) : fname(e.fname), lname(e.lname), job(e.job)  {  }  void abstr_emp::ShowAll() const  {      std::cout << "fname: " << GetFname() << std::endl;      std::cout << "lname: " << GetLname() << std::endl;      std::cout << "job: " << GetJob() << std::endl;  }  void abstr_emp::SetAll()  {      SetFname();      SetLname();      SetJob();  }  std::ostream &operator<<(std::ostream &os, const abstr_emp &e)  {      os << e.fname << ", " << e.lname << ", " << e.job;      return os;  }  abstr_emp::~abstr_emp()  {  }  employee::employee() : abstr_emp()  {  }  employee::employee(const std::string & fn, const std::string & ln, const std::string & j) : abstr_emp(fn, ln, j)  {  }  void employee::ShowAll() const  {      abstr_emp::ShowAll();  }  void employee::SetAll()  {      abstr_emp::SetAll();  }  manager::manager() : abstr_emp()  {      inchargeof = 0;  }  manager::manager(const std::string & fn, const std::string & ln, const std::string & j, int ico) : abstr_emp(fn, ln, j)  {      inchargeof = ico;  }  manager::manager(const abstr_emp & e, int ico) : abstr_emp(e)  {      inchargeof = ico;  }  manager::manager(const manager & m) : abstr_emp((const abstr_emp &)m)  {      inchargeof = m.inchargeof;  }  void manager::ShowAll() const  {      abstr_emp::ShowAll();      std::cout << "inchargeof: " << InChargeOf() << std::endl;  }  void manager::SetAll()  {      abstr_emp::SetAll();      SetInChargeOf();  }  fink::fink() : abstr_emp()  {      reportsto = "NULL";  }  fink::fink(const std::string & fn, const std::string & ln, const std::string & j, const std::string & rpo) : abstr_emp(fn, ln, j)  {      reportsto = rpo;  }  fink::fink(const abstr_emp & e, const std::string & rpo) : abstr_emp(e)  {      reportsto = rpo;  }  fink::fink(const fink & e) : abstr_emp((const abstr_emp &)e)  {      reportsto = e.reportsto;  }  void fink::ShowAll() const  {      abstr_emp::ShowAll();      std::cout << "reportsto" << ReportsTo() <<  std::endl;  }  void fink::SetAll()  {      abstr_emp::SetAll();      SetReportsto();  }  highfink::highfink() : abstr_emp(), manager(), fink()  {  }  highfink::highfink(const std::string & fn, const std::string & ln, const std::string & j, const std::string & rpo, int ico) : abstr_emp(fn, ln, j), manager(fn, ln, j, ico), fink(fn, ln, j, rpo)  {  }  highfink::highfink(const abstr_emp & e, const std::string & rpo, int ico) : abstr_emp(e), manager(e, ico), fink(e, rpo)  {  }  highfink::highfink(const fink & f, int ico) : abstr_emp((const abstr_emp &)f), manager((const abstr_emp &)f, ico), fink(f)  {  }  highfink::highfink(const manager & m, const std::string & rpo) : abstr_emp((const abstr_emp &)m), manager(m), fink((const abstr_emp &)m, rpo)  {  }  highfink::highfink(const highfink & h) : abstr_emp((const abstr_emp &)h), manager((const manager &)h), fink((const fink &)h)  {  }  void highfink::ShowAll() const  {      abstr_emp::ShowAll();      std::cout << "inchargeof: " << InChargeOf() << std::endl;      std::cout << "reportsto: " << ReportsTo() << std::endl;  }  void highfink::SetAll()  {      abstr_emp::SetAll();      manager::SetInChargeOf();      fink::SetReportsto();  }  
//第五题  //main.cpp  #include <iostream>  #include "emp.h"  using namespace std;  int main()  {      employee em("Trip", "Harris", "Thumper");      cout << em << endl;      em.ShowAll();      manager ma("Amorphia", "Spindragon", "Nuancer", 5);      cout << ma << endl;      ma.ShowAll();      fink fi("Matt", "Ogga", "Oiler", "Juno Barr");      cout << fi << endl;      fi.ShowAll();      highfink hf(ma, "Curly Kew");      hf.ShowAll();      cout << "Press a key for next phase:\n";      cin.get();      highfink hf2;      hf2.SetAll();      cout << "Using an abstr_emp * pointer:\n";      abstr_emp *tri[4] = { &em, &fi, &hf, &hf2 };      for (int i = 0; i < 4; ++i)          tri[i]->ShowAll();      return 0;  }  

为什么没有定义赋值运算符?
因为没有涉及到动态分配,使用默认的赋值运算符(浅复制)即可满足需求。
为什么要将ShowAll和SetAll定义为虚?
定义为虚函数时,可以根据指针/引用指向的类型来选择不同的函数。
为什么将abstr_emp定义为虚基类?
这样多重继承(MI)时派生类就只有一个基类的子对象。
为什么highfink类没有数据部分?
因为他的数据成员继承自基类的部分满足该类的功能需求。
为什么只需要一个operator<<()版本?
因为友元函数不能继承,在需要的地方定义即可,不用担心继承关系而重定义以满足不同类的不同需求。
使用新的代码(而不是对象的引用),则调用ShowAll()方法的对象类型为基类(abstremp)类型。
//本章由于学习的不够到位,该章的习题中借鉴了网上的已有的答案,并且学习他们如何使用模板类的方法,改善自己的不足。由于这章并不是独立完成的,代码亦没有改变,下面为引用链接:

http://blog.csdn.net/u012175089/article/details/53914092
http://blog.csdn.net/acm_yuuji/article/details/50185477

阅读全文
0 0
原创粉丝点击