c++ primer plus 第六版第十二章编程练习

12.1

//Cow.h
class Cow
{
	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()const;
};


//Cow.cpp
#pragma warning (disable: 4996)
#include<iostream>
#include<cstring>
using std::cout;
#include "Cow.h"
Cow::Cow()
{
	name[0] = '\0';
	hobby = nullptr;
	weight = 0.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()
{
	delete[]hobby;
}
Cow& Cow::operator=(const Cow &c)
{
	if (this == &c)
		return*this;
	delete[]hobby;
	hobby = new char[strlen(c.hobby) + 1];
	strcpy(hobby, c.hobby);
	strcpy(name, c.name);
	weight = c.weight;
	return *this;
}
void Cow:: ShowCow()const
{
	cout << "name: " << name
		<< "\nhobby: " << hobby
		<< "\nweight: " << weight
		<< std::endl;
}
// main.cpp: 
#pragma warning (disable: 4996)
#include<iostream>
#include"Cow.h"
using std::cout;
using std::cin;
using std::endl;
int main()
{
	Cow c1;//调用默认构造函数
	Cow c2("Susan", "eating", 150.4);//构造函数
	Cow c3 = c2;//用已有对象初始化新的类对象,调用复制构造函数
	c1 = c3;//对已有的对象重新赋值,调用重载的赋值函数;
	cout << "c1:\n";
	c2.ShowCow();
	cout << "c2:\n";
	c2.ShowCow();
	cout << "c3:\n";
	c3.ShowCow();
    return 0;
}

12.2

//string2.h
#ifndef STRING_H_
#define STRING_H_
#include<iostream>
using std::ostream;
using std::istream;
class String
{
public:
	String(const char *s);
	String();
	String(const String &st);
	~String();
	int length()const { return len; };
	void Stringlow();
	void Stringupper();
	int has(const char ch);
	String & operator=(const String &st);
	String & operator=(const char *s);
	char& operator[](int i);
	const char & operator[](int i)const;
	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 String operator+(const String&st1, const String &st2);
	friend String operator+(const char *st1, const String &st2);
	friend ostream& operator<<(ostream&os, const String&st);
	friend istream& operator>>(istream&is, String&st);
	static int HowMany();
private:
	char *str;
	int len;
	static int num_strings;
	static const int CINLIM = 80;
};
#endif // !STRING_H_
//string2.cpp
#pragma warning (disable: 4996)
#include<iostream>
#include<cstring>
#include<cctype>
#include"string2.h"

int String::num_strings = 0;
String::String(const char *s)
{
	len = strlen(s);
	str = new char[len + 1];
	strcpy(str, s);
	num_strings++;
}
String::String()
{
	len = 4;
	str = new char[1];
	str[0] = '\0';
	num_strings++;
}
String::String(const String &st)
{
	len = st.len;
	str = new char[len + 1];
	strcpy(str, st.str);
	num_strings++;
}

String::~String()
{
	delete[]str;
	--num_strings;
}

void String::stringlow()
{

	for (int i = 0; str[i] != '\0'; i++) {
		if (isalpha(str[i]))
			str[i] = tolower(str[i]);

	}
}

void String::stringup()
{

	for (int i = 0; str[i] != '\0'; i++)
	{
		if (isalpha(str[i]))
			str[i] = toupper(str[i]);

	}
}

int String::has(const char ch)
{
	int times = 0;
	for (int i = 0; str[i] != '\0'; i++)
	{
		if (str[i] == ch)
			times++;
	}
	return times;
}

String& String::operator=(const String &st)
{
	if (this == &st)
		return*this;
	delete[] str;
	len = st.len;
	str = new char[len + 1];
	strcpy(str, st.str);
	return*this;
}
String &String:: operator=(const char *s)
{
	delete[]str;
	len = strlen(s);
	str = new char[len + 1];
	strcpy(str, s);
	return*this;
}
char& String:: operator[](int i)
{
	return str[i];
}
const char & String::operator[](int i)const
{
	return str[i];
}
bool operator<(const String &st1, const String&st2)
{
	return(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 (strcmp(st1.str, st2.str) == 0);
}


String operator+(const String &st1, const String &st2)
{
	String s;
	s.len = st1.len + st2.len;
	delete[]s.str;//默认构造的st3分配的动态内存不够,必须重新分配
	s.str = new char[s.len + 1];
	strcpy(s.str, st1.str);
	strcat(s.str, st2.str);
	return s;
}


ostream& operator<<(ostream&os, const String&st)
{
	os << st.str;
	return os;
}
istream& operator>>(istream&is, String&st)
{
	char temp[String::CINLIM];
	is.get(temp, String::CINLIM);
	if (is)
	{
		st = temp;
        /*直接调用重载运算符=函数相当于st.operator(temp) ,因此也无需加st.len = strlen(st.str);
		会在重载运算中对其重新赋值;
		不能用st.str = temp;这是传递地址,使得str的地址等于temp的,
		但是temp是局部变量,会在函数完成之后释放内存,从而导致参数传递错误
		*/ 
		st.len = strlen(st.str);
	}
	while (is&&is.get() != '\n')
		continue;
	return is;
}
int  String::HowMany()
{
	return num_strings;
}


//main.cpp
#include <iostream>
using namespace std;
#include "String2.h"
int main()
{
	String s1(" and I am a C++ student.");
	String s2 = "Please enter your name: ";
	String s3;
	cout << s2;
	cin >> s3;
	s2 = "My name is " + s3;
	cout << s2 << ".\n";
	s2 = s2 + s1;
	s2.stringup();
	cout << "The string\n" << s2 << "\ncontains " << s2.has('A')
		<< " 'A' characters in it.\n";

	s1 = "red";
	String rgb[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!\n";
				success = true;
				break;
			}
		}
		if (success)
			break;
		else
			cout << "Try again!\n";
	}
	cout << "Bye\n";
	return 0;
}

12.3

//stock.h
#ifndef STOCK20_H_
#define STOCK20_H_
#include<iostream>
class Stock
{
public:
	Stock();
	Stock(const char * co, long n = 0, double pr = 0.0);
	~Stock();
	void buy(long num, double price);
	void sell(long num, double price);
	void update(double price);
	const Stock&topval(const Stock&s)const;
	friend std::ostream& operator<<(std::ostream &os, const Stock &s);
private:
	char *company;
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }

};

#endif // !STOCK@)_H_

//stock.cpp

#include<ctring>
#include"stock.h"
Stock::Stock()
{
	company = new char[1];
	company[0] = '\0';
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}
Stock::Stock(const char * co, long n, double pr )
{
	int len;
	len= std::strlen(co) + 1;
	company = new char[len];
	strcpy(company, co);
	if (n < 0)
	{
		std::cout << "number of shares can't be negative;"
			<< company << "shares sset to 0.\n";
		shares = 0;
	}
	else
	{
		shares = n;
	}
	share_val = pr;
	set_tot();
}
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.\n";
	}
	else
	{
		shares += num;
		share_val = price;
		set_tot();
	}
}
void Stock::sell(long num, double price)
{
	using std::cout;
	if (num < 0)
	{
		cout<<"Number of shares sold can't be negative."
			<< "Transaction is aborted.\n";
	}
	else if(num>shares)
	{
		cout << "You can't sell more than you hanve!"
			<< "Transaction is abotrted.\n";
	}
	else
	{
		shares -= num;
		share_val = price;
		set_tot();
	}
}
void Stock::update(double price)
{
	share_val = price;
	set_tot();
}
const Stock&Stock::topval(const Stock&s)const
{
	if (s.total_val > total_val)
		return s;
	else
		return*this;
}
std::ostream& operator<<(std::ostream &os, const Stock &s)
{
	using std::ios_base;
	ios_base::fmtflags orig =
		os.setf(ios_base::fixed, ios_base::floatfield);
	std::streamsize prec = os.precision(3);

	os << "company: " << s.company
		<< " shares: " << s.shares << '\n';
	os << " Share price: $" << s.share_val;
	os.precision(2);
	os << " Total Worth: $" << s.total_val << '\n';
	os.setf(orig, ios_base::floatfield);
	os.precision(prec);
}
//main.cpp
#include<iostream>
#include"stock.h"
const int STKS = 4;
int main()
{
	Stock stock[STKS] =
	{
		Stock("NanoSmart",12,20.0),
		Stock("Boffo Objects",200,2.0),
		Stock("Monolithic Obelisks",130,3.25),
		Stock("Fleep Enterprises",60,6.5)
	};
	std::cout << "Stock holdings:\n";
	int st;
	for (st = 0; st < STKS; st++)
		std::cout << stock[st];
	const Stock* top = &stock[0];
	for (st = 1; st < STKS; st++)
	{
		top = &top->topval(stock[st]);
	}
	std::cout << "\nMost valuable holding:\n"
		<< *top;//若将*top改为top将输出地址而不是内容
	std::cin.get();//若运行程序是闪退,可加上这条语句
	return 0;
}

12.4

//stack.h
#include<iostream>
typedef unsigned long Item;
class Stack
{
private:
	enum { MAX = 10 };
	Item *pitems;
	int size;
	int top;
public:
	Stack(int n = MAX);
	Stack(const Stack &st);
	~Stack();
	bool isempty()const;
	bool isfull()const;
	bool push(const Item & item);
	bool pop(Item & item);
	Stack & operator=(const Stack &st);
	friend std::ostream& operator<<(std::ostream&os, const Stack&st);
};
//stack.cpp
#include<iostream>
#include<cstring>
#include"stack.h"
Stack::Stack(int n)
{
	pitems = new Item[n];
	size = top = 0;
}
Stack::Stack(const Stack &st)
{
	pitems = new Item[MAX];
	size = st.size;
	top = st.top;
	for (int i = 0; i < size; i++)
	{
		pitems[i] = st.pitems[i];
	}
}
Stack::~Stack()
{
	delete[]pitems;//将栈删除那size、top是在运行完后删除?所定义的stack失效后删除
}
bool Stack::isempty()const
{
	return top == 0;
}
bool Stack::isfull()const
{
	return top == MAX;
}
bool Stack::push(const Item & item)
{
	if (isfull())
	{
		std::cout << "stack has full\n";
		return false;
	}
	else
	{
		top++;
		pitems[top] = item;
		size++;
		return true;
	}
}
bool Stack::pop(Item & item)
{
	if (isempty())
	{
		std::cout << "stack is empty.\n";
		return false;
	}
	else
	{
		item = pitems[top];
		top--;
		size--;
		return true;
	}
}
Stack &Stack:: operator=(const Stack &st)
{
	if (this == &st)
		return*this;
	delete[] pitems;
	pitems = new Item[MAX];//怎么创建不是MAX的stack?
	for (int i = 0; i < st.size; i++)
		pitems[i] = st.pitems[i];
	top = st.top;
	size = st.size;
	return *this;
}
std::ostream& operator<<(std::ostream&os, const Stack&st)
{
	os << "stack includes:\n";
	for (int i = 0; i < st.size; i++)
		os << "#" << i + 1 << ": " << st.pitems[i]<<std::endl;
	return os;
}
//stackmain.cpp
#include<iostream>
#include"stack.h"
int main()
{
	using namespace std;
	Stack s1;
	unsigned long po;
	cout << "enter number to push.\n";
	while (!s1.isfull()&&cin>>po)
	{
		s1.push(po);
	}
	cout << "s1 " << s1;
	Stack s2 = s1;//调用复制构造函数;
	cout << "s2 " << s2;
	Stack s3;
	s3 = s2;
	return 0;
} 

12.6

//queue.h
#ifndef QUEUE_H_
#define QUEUE_H_
class Customer
{
public:
	Customer() { arrive = processtime = 0; }
	void set(long when);
	long when()const { return arrive; }
	int ptime()const { return processtime; }
private:
	long arrive;
	int processtime;
};
typedef Customer Item;
class Queue
{
private:
	struct Node { Item item; struct Node* next; };
	enum {Q_SIZE =10};
	Node * front;
	Node * rear;
	int items;
	const int qsize;
	Queue(const Queue &q) :qsize(0) {};
	Queue &operator=(const Queue &q) { return *this; }
public:
	Queue(int qs = Q_SIZE);
	~Queue();
	bool isempty()const;
	bool isfull()const;
	int queuecount()const;
	bool enqueue(const Item&item);
	bool dequeue(Item &item);
	friend bool operator>(const Queue &item1, const Queue &item2);
};
#endif // !QUEUE_H_
//queue.cpp
#include"queue.h"
#include<cstdlib>
Queue::Queue(int qs):qsize(qs)
{
	front = rear = nullptr;
	items = 0;
}
Queue::~Queue()
{
	Node*temp;
	while (front!=nullptr)
	{
		temp = front;
		front = front->next;
		delete temp;
	}
}
bool Queue::isempty()const
{
	return items == 0;
}
bool Queue::isfull()const
{
	return items == qsize;
}
int Queue::queuecount()const
{
	return items;
}
bool Queue::enqueue(const Item&item)
{
	if (isfull())
		return false;
	Node * add = new Node;
	add->item = item;
	add->next = nullptr;
	items++;
	if (front = nullptr)
		front = add;
	else
		rear->next = add;
	rear = add;
	return true;
}
bool Queue::dequeue(Item &item)
{
	if (isempty())
		return false;
	item= front->item;
	items--;
	Node *temp = front;
	front = front->next;
	delete temp;
	if (items == 0)
		rear =nullptr;
	return true;
}
void Customer::set(long when)
{
	processtime = std::rand() % 3 + 1;
	arrive = when;
}
bool operator>(const Queue &item1, const Queue &item2)
{
	return item1.items > item2.items;
}
//main.cpp
#include<iostream>
#include<cstdlib>
#include<ctime>
#include"queue.h"
const int MIN_PER_HR=60;
bool newcustomer(double x)
{
	return (std::rand() * x / RAND_MAX < 1);
}
int main()
{
	using std::cin;
	using std::cout;
	using std::endl;
	using std::ios_base;
	std::srand(std::time(0));
	cout << "Case Study: Bank of Heather Automatic Teller\n";
	cout << "Enter maximun size of queue: ";
	int qs;
	cin >> qs;
	Queue line1(qs);
	Queue line2(qs);
	cout << "Enter the number od simulation hours: ";
	int hours;
	cin >> hours;
	long cyclelimit = MIN_PER_HR * hours;
	cout << "enter the average number of customers per hour: ";
	double perhour;
	cin >> perhour;
	double min_per_cust;
	min_per_cust = MIN_PER_HR / perhour;
	Item temp;
	long turnaways = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait1_time = 0;
	int wait2_time = 0;
	long line1_wait = 0;
	long line2_wait = 0;
	for (int cycle = 0; cycle < cyclelimit; cycle++)//执行一次一分钟,怎么实现?
	{
		if (newcustomer(min_per_cust))//有顾客到来
		{
			if (line1.isfull() && line2.isfull())//两队都已排满
				turnaways++;
			else if(line2>line1||line2.isfull())//新顾客排第一队
			{
				customers++;
				temp.set(cycle);//设置顾客到达的时间为当前循环次数
				line1.enqueue(temp);
			}
			else//顾客排第二队
			{
				customers++;
				temp.set(cycle);
				line2.enqueue(temp);
			}
		}
		if (wait1_time <= 0 && !line1.isempty())//没有顾客在进行交易
		{
			line1.dequeue(temp);//顾客离队,进行交易
			wait1_time = temp.ptime();//重新设置line1的状态为正在交易,需等待的时间是当前顾客的交易时间
			line1_wait += cycle - temp.when();//目前为止line1总共的等待时间
		}
		if (wait2_time <= 0 && !line1.isempty())//没有顾客在进行交易
		{
			line2.dequeue(temp);
			wait2_time = temp.ptime();
			line2_wait += cycle - temp.when();
		}
		if (wait1_time > 0)//line1正在交易
			wait1_time--;//需等待时间减一次循环(一分钟)
		sum_line += line1.queuecount();//更新积累的排队长度
		if (wait2_time > 0)
			wait2_time--;
		sum_line += line2.queuecount();
	}
	if (customers > 0)
		{
			cout << "customers accepted: " << customers << endl;
			cout << "  customers served: " << served << endl;
			cout << "         turnaways: " << turnaways << endl;
			cout << "average queue size: ";
			cout.precision(2);
			cout.setf(ios_base::fixed, ios_base::floatfield);
			cout << (double)sum_line / cyclelimit << endl;
			cout << " average wait time: "
				<< (double)(line1_wait + line2_wait) / served << " minutes\n";
		}
	else
		cout << "No customers!\n";
	cout << "Done!\n";
	return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值