C++ primer plus 第14章习题

本文通过具体的代码示例,展示了C++中模板类的应用及多重继承的实现方式,包括自定义Pair类、Wine类的实现,以及Worker类族的多态特性与队列类的设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//第14章第1题
#ifndef WINE_H_
#define WINE_H_

#include<iostream>
#include<string>
#include<valarray>
//#include<utility>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template <class T1,class T2>
class Pair
{
private:
	T1 a;
	T2 b;
public:
	T1 &first();
	T2 &second();//返回引用
	T1 first()const { return a; }
	T2 second()const { return b; }//直接返回
	Pair(const T1 &aval, const T2 &bval) :a(aval), b(bval){}//初始化
	Pair(){}
	void setFirst(const T1&t1)
	{
		a = t1;
	}
	void setSecond(const T2&t2)
	{
		b = t2;
	}
};
template<class T1,class T2>
T1 &Pair<T1, T2>::first()
{
	return a;
}
template<class T1, class T2>
T2 &Pair<T1, T2>::second()
{
	return b;
}
typedef std::valarray<int>ArrarInt;
typedef Pair<std::valarray<int>, std::valarray<int>>PairArray1;//最好用这个
//typedef std::pair<std::valarray<int>, std::valarray<int>>PairArray;
class Wine 
{
private:
	string name;
	PairArray1 pa;
	int wyr;
public:
	Wine(const char *l, int y, const int yr[], const int bot[])
	{
		name = l;//可以直接赋值
		wyr = y;
	/*	pa.first = yr;
		pa.second = bot;*///这个编译不通过,所以要换
		ArrarInt  f(yr, y);
		ArrarInt  b(bot, y);
		pa.setFirst(f);
		pa.setSecond(b);//不过也有人用make_pairs
		/*pa = std::make_pair(f, b);*///这个要用其他宏定义,
	}
	Wine(const char *l, int y)
	{
		name = l;
		wyr = y;
		pa.setFirst(ArrarInt(y));
		pa.setSecond(ArrarInt(y));
	}
	void GetBottles()
	{
		cout << "Please enter number of"<<wyr<<" yesrs:\n";
		for (int i = 0; i < wyr; i++)
		{
			cout << "Enter year:";
			cin >> pa.first()[i];//返回的是数组,可以这样写
			cin.get();//吃回车,不然就down
			cout << "Enter bottles for that year:";
			cin >> pa.second()[i];
			cin.get();//吃回车,不然就down
		}
	}
	int sum()
	{
		return pa.second().sum();//返回数组的sum方法
	}
	string & Label()
	{
		return name;
	}
	void Show()
	{
		cout << "Wine: " << name << endl;
		cout << "     " << "Year" << "   " << "Bottles" << endl;
		for (int i = 0; i < wyr; i++)
		{
			cout << "     " << pa.first()[i] << "   " << pa.second()[i] << endl;
		}

	}

};

#endif



//第14章第1题,第2题
#include<iostream>
#include"interface.h"
#include<stdlib.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 wine:";
	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("Gusing Grape Red", YRS, y, b);
	more.Show();
	cout << "Total bottles for" << more.Label() << ": " << more.sum() << endl;
	cout << "bye!\n";
	system("pause");
	return 0;
}


//第14章第2题
#ifndef WINE_H_
#define WINE_H_

#include<iostream>
#include<string>
#include<valarray>
//#include<utility>
using std::cin;
using std::cout;
using std::endl;
using std::string;
template <class T1, class T2>
class Pair
{
private:
	T1 a;
	T2 b;
public:
	T1 &first();
	T2 &second();//返回引用
	T1 first()const { return a; }
	T2 second()const { return b; }//直接返回
	Pair(const T1 &aval, const T2 &bval) :a(aval), b(bval){}//初始化
	Pair(){}
	void setFirst(const T1&t1)
	{
		a = t1;
	}
	void setSecond(const T2&t2)
	{
		b = t2;
	}
};
template<class T1, class T2>
T1 &Pair<T1, T2>::first()
{
	return a;
}
template<class T1, class T2>
T2 &Pair<T1, T2>::second()
{
	return b;
}
typedef std::valarray<int>ArrarInt;
typedef Pair<ArrarInt, ArrarInt>PairArray;//最好用这个

class Wine : private std::string, private PairArray//这样没错,为何不能继承模板
{
private:
	string name;
	//PairArray pa;
	int wyr;
public:
	Wine(const char *l, int y, const int yr[], const int bot[])
	{
		name = l;//可以直接赋值
		wyr = y;
		/*	pa.first = yr;
		pa.second = bot;*///这个编译不通过,所以要换
		ArrarInt  f(yr, y);
		ArrarInt  b(bot, y);
		PairArray::setFirst(f);
		PairArray::setSecond(b);//不过也有人用make_pairs
		/*pa = std::make_pair(f, b);*///这个要用其他宏定义,
	}
	Wine(const char *l, int y)
	{
		name = l;
		wyr = y;
		PairArray::setFirst(ArrarInt(y));
		PairArray::setSecond(ArrarInt(y));
	}
	void GetBottles()
	{
		cout << "Please enter number of" << wyr << " yesrs:\n";
		for (int i = 0; i < wyr; i++)
		{
			cout << "Enter year:";
			cin >> PairArray::first()[i];//返回的是数组,可以这样写
			cin.get();//吃回车,不然就down
			cout << "Enter bottles for that year:";
			cin >> PairArray::second()[i];
			cin.get();//吃回车,不然就down
		}
	}
	int sum()
	{
		return PairArray::second().sum();//返回数组的sum方法
	}
	string & Label()
	{
		return name;
	}
	void Show()
	{
		cout << "Wine: " << name << endl;
		cout << "     " << "Year" << "   " << "Bottles" << endl;
		for (int i = 0; i < wyr; i++)
		{
			cout << "     " << PairArray::first()[i] << "   " << PairArray::second()[i] << endl;
		}

	}

};

#endif


//第14章第1题,第2题
#include<iostream>
#include"interface.h"
#include<stdlib.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 wine:";
	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("Gusing Grape Red", YRS, y, b);
	more.Show();
	cout << "Total bottles for" << more.Label() << ": " << more.sum() << endl;
	cout << "bye!\n";
	system("pause");
	return 0;
}


//第14章第3题
#ifndef WORK_H_
#define WORK_H_

#include<string>
using std::string;
class Worker
{
private:
	string fullname;
	long id;
protected:
	virtual void Data()const;
	virtual void Get();
public:
	Worker() :fullname("no one"), id(0l){}
	Worker(const 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//worker 为虚基类
{
private:
	int panache;
protected:
	void Data()const;
	void Get();//发生多态
public:
	Waiter() :Worker(), panache(0){}
	Waiter(const 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 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 SingerWaiter : public Singer, public Waiter
{
protected:
	void Data()const;
	void Get();
public:
	SingerWaiter(){}
	SingerWaiter(const string &s, long n, int p = 0, int v = other) :Worker(s, n), Waiter(s, n, p), Singer(s, n, v){}
	SingerWaiter(const Worker &wk, int p = 0, int v = other) :Worker(wk), Waiter(wk, p), Singer(wk, v){}
	SingerWaiter(const Waiter &wt, int v = other) :Worker(wt), Waiter(wt), Singer(wt, v){}
	SingerWaiter(const Singer &wt, int p=0) :Worker(wt), Singer(wt), Waiter(wt, p){}
	void Set();
	void Show()const;

};
#endif

////第14章第3题
#include"interface.h"
#include<iostream>
using std::cin;
using std::cout;
using std::endl;

Worker::~Worker(){}
void Worker::Data()const
{
	cout << "Name:" << fullname << endl;
	cout << "Employee ID:" << id << endl;
}
void Worker::Get()
{
	getline(cin, fullname);
	cout << "Enter worker's ID:";
	cin >> id;
	while (cin.get() != '\n')
		continue;
}
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;
}

void Waiter::Set()
{
	cout << "Enter waiter's name:";
	Worker::Get();
	Get();
}
void Waiter::Show()const
{
	cout << "Category:waiter\n";
	Worker::Data();
	Data();
}

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)
		cin >> voice;
	while (cin.get() != '\n')
		continue;
}

void SingerWaiter::Set()
{
	cout << "Enter singing waiters name:";
	Worker::Get();
	Get();
}
void SingerWaiter::Show()const
{
	cout << "Category:singing waiter\n";
	Worker::Data();
	Data();
}
void SingerWaiter::Data()const
{
	Singer::Data();
	Waiter::Data();
}
void SingerWaiter::Get()
{
	Waiter::Get();
	Singer::Get();
}



////第14章第3题
#ifndef QUEUE_H_
#define QUEUE_H_

template <class T>
class Queue
{
private:
	struct Node{ T *item; struct Node *next; };//包含数据,和一个指向下个数据块的指针
	enum { Q_SIZE = 10 };
	Node *front;//第一个
	Node *rear;//最后一个
	int items; //总序列号
	const int qsize=5;//最大序列号//当初忘了初始化,悲催
public:
	Queue()//构造函数
	{
		front = rear = NULL;
		items = 0;
	}
	~Queue()
	{
		Node * temp;
		while (front != NULL)
		{
			temp = front;//先保存
			front = front->next;//后讲第二个设置为第一个
			delete temp;//把第一个删除
		}
	}
	bool isempty()const   //是否为空
	{
		return items == 0;
	}
	bool isfull()const   //是否为满
	{
		return items == qsize;
	}
	int queuecount()const//计数
	{
		return items;
	}
	bool enqueue(T *item)//增加
	{
		if (isfull())
			return false;//先判断是否满
		Queue::Node *add = new Queue::Node;//创建新结点
		add->item = item;//加顾客
		add->next = NULL;
		items++;
		if (front == NULL)
			front = add;
		else
			rear->next = add;//把尾地址给add连在一起
		rear = add;//将add变为尾部
		return true;
	}
	bool dequeue(T *item)//这种弄成内联函数,并且不能用const
	{
		if (front == NULL)
			return false;
		item = front->item;
		items--;
		Queue::Node *temp = front;
		front = front->next;
		delete temp;
		if (items == 0)
			rear = NULL;
		return true;
	}
};//少了分号,报错了
#endif


//////第14章第3题
#include <iostream>
#include "queue.h"
#include "interface.h"
#include <string>
#include<stdlib.h>
using std::cin;
using std::cout;
using std::endl;
const int SIZE = 5;
void main()
{
	Queue<Worker*> line;//注意类型应为Worker*
	Worker *lolas[SIZE];

	int ct;
	for (ct = 0; ct<SIZE; ct++)
	{
		char choice;
		cout << "Enter the employee category:" << endl
			<< "w:waiter     s:singer    " 
			<< "t:singerWaiter    q:quit" << endl;
		cin >> choice;
		while (strchr("wstq", choice) == NULL)//p564关于strchr有解释
		{
			cout << "Please enter a w,s,t or q:";
			cin >> choice;
		}
		if (choice == 'q')
			break;
		switch (choice)
		{
		case 'w':lolas[ct] = new Waiter; break;
		case 's':lolas[ct] = new Singer; break;
		case 't':lolas[ct] = new SingerWaiter; break;

		}
		cin.get();
		lolas[ct]->Set();//多态
		line.enqueue(&lolas[ct]);//加入队列
	}
	cout << "Here is your staff:" << endl;
	int i;
	for (i = 0; i<ct; i++)
	{
		lolas[i]->Show();
		cout << endl;
	}
	cout << endl;
	cout << "Next is the line:" << endl;
	system("pause");
};

//第4题
#ifndef PERSON_H_
#define PERSON_H_
#include<string>
#include<iostream>
#include<ctime>
using std::string;
using std::cin;
using std::cout;
using std::endl;
class Person
{
private:
	string  firstname;
	string  lastname;
public:
	Person() :firstname("w"), lastname("qf"){}
	Person(const string &f, const string &l) :firstname(f), lastname(l){}
	virtual void Show()
	{
		cout << "Firstname:" << firstname << " Lastname:" << lastname << endl;
	}
};
class Gunslinger : virtual public Person
{
private:
	int pnum;
	double ptime;
public:
	Gunslinger() :Person(), pnum(0), ptime(0){}
	Gunslinger(const Person &gl, int p, double pt) :Person(gl), pnum(p), ptime(pt){}
	Gunslinger(const string &f, const string &l, int p, double pt) :Person(f, l), pnum(p), ptime(pt){}
	double Draw()
	{
		return ptime;
	}
	void Show()
	{
		Person::Show();
		cout << "Pnum:" << pnum << "  Ptime:" << ptime << endl;
	}
};
class PokerPlayer :public virtual Person
{
public:
	PokerPlayer() :Person(){}
	PokerPlayer(const string &f, const string &l) :Person(f,l){}
	int Draw()
	{
		return rand() % 52;
	}
	void Show()
	{
		Person::Show();
	}
};

class BadDude :public PokerPlayer, public Gunslinger
{
public:
	BadDude() :Person(), Gunslinger(), PokerPlayer(){}
	BadDude(const string &s,const string &l) :Person(s,l){}
	BadDude(const string &s, const string &l, int p, double pt) :Person(s, l), Gunslinger(s, l, p, pt){}
	BadDude(const Person &f, int p, double pt) :Person(f), Gunslinger(f, p, pt){}
	BadDude(const Gunslinger &gl) :Gunslinger(gl){}
	double Gdraw()
	{
		return Gunslinger::Draw();
	}
	int Cdraw()
	{
		return PokerPlayer::Draw();
	}
	void Show()
	{
		Person::Show();
		cout << "GdrawTime:" << Gdraw() << endl;
		cout << "CdrawTime:" << Cdraw() << endl;
	}
};
#endif


//第4题
#include<stdlib.h>
#include<iostream>
#include"interface.h"
int main()
{
	Person p("W", "QF");
	Gunslinger g("H", "HJ", 3, 1.2);
	PokerPlayer po("L", "QQ");
	BadDude b("C", "WH", 2, 1.1);
	Person *ptr = &p;
	ptr->Show();
	ptr = &g;
	ptr->Show();
	ptr = &po;
	ptr->Show();
	ptr = &b;
	ptr->Show();
	system("pause");
	return 0;
}


//第5题
#ifndef CHILD_H
#define CHILD_H
#include<iostream>
#include<string>

using std::string;
using std::cin;
using std::cout;
using std::endl;
class abstr_emp
{
private:
	string fname;
	string lname;
	string job;
protected:
	void Setfname(){ cout << "Input fname"; std::getline(cin, fname); }
	void Setlname(){ cout << "Input lname"; std::getline(cin, lname); }
	void Setjob(){ cout << "Input job"; std::getline(cin, job); }
public:
	abstr_emp();
	abstr_emp(const string &fn, const string &ln, const string &j);
	virtual void ShowAll()const;
	virtual void SetAll();
	friend std::ostream &operator<<(std::ostream &os, const abstr_emp &e);
	virtual ~abstr_emp(){};
};
class employee: public abstr_emp
{
public :
	employee();
	employee(const string &fn, const string &lv, const 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 &InChargeOf(){ return inchargeof; };
	void SetInChargeOf()
	{
		cout << "Input Inchargeof:";
		cin >> inchargeof;
		cin.get();
	}
public:
	manager();
	manager(const string &fn, const string &ln, const string &j, int ico=0);
	manager(const manager &m);
	manager(const abstr_emp & e, int ico);
	~manager(){}
	virtual void ShowAll()const;
	virtual void SetAll();
};
class fink :virtual public abstr_emp
{
private:
	string resportsto;
protected:
	string ResportSto()const { return resportsto; };
	string &ResoprtSto(){ return resportsto; };
	void SetReportsto()
	{
		cout << "Setreportsto:";
		getline(cin, resportsto);
		cin.get();
	}
public:
	fink();
	fink(const string &fn, const string &ln, const string &j, const string &rpo);//这个必须是const,不然报错
	fink(const abstr_emp &e, const string &rpo);
	fink(const fink &e);
	~fink(){}
	virtual void ShowAll()const;
	virtual void SetAll();
};
class highfink :public manager, public fink
{
public:
	highfink();
	highfink(const string &fn, const string &ln, const string &j, const string &rpo);
	highfink(const fink &f, int ico);
	highfink(const abstr_emp &e, const string &rpo, int ico);
	highfink(const manager &m, const string &rpo);
	highfink(const highfink &h);
	~highfink(){}
	virtual void ShowAll()const;
	virtual void SetAll();
};
#endif



//第5题
#include<iostream>
#include"interface.h"

using std::cin;
using std::cout;
using std::endl;

abstr_emp::abstr_emp()
{
	fname = "fdefault";
	lname = "ldefault";
	job = "jdefault";
}
abstr_emp::abstr_emp(const string &fn, const string &ln, const string &j)
{
	fname = fn;
	lname = ln;
	job = j;
}
void abstr_emp::ShowAll()const
{
	cout << "fname:" << fname << endl;
	cout << "lname:" << lname << endl;
	cout << "job:" << job << 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;
}
employee::employee() :abstr_emp(){}
employee::employee(const string &fn, const string &lv, const string &j) : abstr_emp(fn, lv, j){}
void employee::ShowAll()const
{
	abstr_emp::ShowAll();
}
void employee::SetAll()
{
	abstr_emp::SetAll();
}



manager::manager() :abstr_emp(){ inchargeof = 0; }
manager::manager(const string &fn, const string &ln, const string &j, int ico) : abstr_emp(fn, ln, j){ inchargeof = ico; }
manager::manager(const manager &m) : abstr_emp(m), inchargeof(m.inchargeof){}
manager::manager(const abstr_emp & e, int ico) : abstr_emp(e), inchargeof(ico){}
void manager::ShowAll()const
{
	abstr_emp::ShowAll();
	cout << "Inchargeof:" << inchargeof << endl;
}
void manager::SetAll()
{
	abstr_emp::SetAll();
	SetInChargeOf();
}


fink::fink() :abstr_emp(){}
fink::fink(const string &fn, const string &ln, const string &j, const string &rpo) : abstr_emp(fn, ln, j), resportsto(rpo){}
fink::fink(const abstr_emp &e, const string &rpo) : abstr_emp(e), resportsto(rpo){}
fink::fink(const fink &e) : abstr_emp(e)
{
	resportsto = e.resportsto;
}
void fink::ShowAll()const
{
	abstr_emp::ShowAll();
	cout << "resportsto:" << resportsto << endl;
}
void fink::SetAll()
{
	abstr_emp::SetAll();
	SetReportsto();
}


highfink::highfink() :abstr_emp(), manager(), fink(){}
highfink::highfink(const string &fn, const string &ln, const string &j, const string &rpo) : abstr_emp(fn, ln, j), fink(fn,ln,j,rpo){}
highfink::highfink(const fink &f, int ico) : abstr_emp(f), fink(f), manager((abstr_emp &)f, ico){}
highfink::highfink(const abstr_emp &e, const string &rpo, int ico) : abstr_emp(e), fink(e,rpo), manager(e, ico){}
highfink::highfink(const manager &m, const string &rpo) : abstr_emp(m), fink((abstr_emp &)m,rpo), manager(m){}
highfink::highfink(const highfink &h) : abstr_emp(h), manager((manager &)h), fink((fink &)h){}
void highfink::ShowAll()const
{
	abstr_emp::ShowAll();
	cout << "Inchargeof:" << InChargeOf() << endl;
	cout << "reportrto:" << ResportSto() << endl;
}
void highfink::SetAll()
{
	abstr_emp::SetAll();
	manager::SetInChargeOf();
	fink::SetReportsto();
}



//第5题
#include<iostream>
#include<stdlib.h>
#include"interface.h"
using namespace std;
int main()
{
	employee em("Trip", "Harris", "Thumper");
	cout << em << endl;
	em.ShowAll();
	manager ma("Amorphia", "Spindragon", "Nuancer", 5);
	cout <<endl<< ma << endl;
	ma.ShowAll();

	fink fi("Matt", "Oggs", "Oiler", "Juno Barr");
	cout <<endl<<fi << endl;
	fi.ShowAll();
	highfink hf(ma, "Curly Kew");
	cout << endl;
	hf.ShowAll();
	cout << endl;
	cout << "Press a key for next phase:\n";
	cin.get();
	highfink hf2;
	hf2.SetAll();
	
	cout <<endl<< "Using an abstr_emp * pointer :";
	abstr_emp *tri[4] = { &em, &fi, &hf, &hf2 };
	for (int i = 0; i < 4; i++)
	{
		tri[i]->ShowAll();
		cout << endl;
	}
	system("pause");
	return 0;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值