欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++PrimerPlus第六版第十二章类和动态内存分配编程练习答案

程序员文章站 2022-07-14 20:11:43
...

1.

Cow.h

#ifndef Cow_H_
#define Cow_H_
#include<iostream>
using std::cout;
using std::endl;
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() const;
};
Cow::Cow()
{
	strcpy_s(name, 20, "helloWorld!");
	hobby = nullptr;
	weight = 0.0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
	strcpy_s(name,20,nm);
	int len = strlen(ho);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1,ho);
	weight = wt;


}
Cow::Cow(const Cow & c)
{
	strcpy_s(name, 20,c.name);
	int len = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1, c.hobby);
	weight = c.weight;
}
Cow::~Cow()
{
	delete[]hobby;
}
Cow & Cow::operator = (const Cow & c)
{
	if (this == &c)
	{
		return *this;
	}
	delete[] hobby;
	strcpy_s(name,20, c.name);
	int len = strlen(c.hobby);
	hobby = new char[len + 1];
	strcpy_s(hobby, len + 1, c.hobby);
	weight = c.weight;
	return  *this;
}
void Cow::ShowCow() const
{
	cout << "name: " << name << '\n'
		<< "hobby: " << hobby << '\n'
		<< "weight: " << weight << endl;
}
#endif // Cow_H_

main.cpp

#include "Cow.h"

int main()
{
	Cow a;
	Cow b("jack", "study", 120);
	b.ShowCow();
	a = b;
	a.ShowCow();
	Cow c(a);
	c.ShowCow();
	return 0;
}

2.

String.h

#ifndef STRING2_H_H
#define STRING2_H_H

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using std::ostream;
using std::istream;
class String
{
private:
	char * str;
	int len;
	static int num_strings;
	static const int CINLIM = 80;
public:

	String(const char *s);
	String();
	String(const String &);
	~String();
	int length()const { return len; }

	String & operator= (const String &);
	String & operator= (const char *);
	char & operator[] (int i);
	const char & operator[](int i) const;
	friend bool operator<(const String & st, const String &st2);
	friend bool operator>(const String & st, const String &st2);
	friend bool operator==(const String & st, const String &st2);
	friend ostream & operator<<(ostream & os, const String & st);
	friend istream & operator>>(istream & is, String & st);
	static int Howmany();


	friend String operator+(const char * s, const String & st);
	friend String operator+(const String & st, const String &st1);


	void stringlow();
	void stringup();
	int count(char);
};

int String::num_strings = 0;
int String::Howmany()
{
	return num_strings;
}
String::String(const char *s)
{
	len = std::strlen(s);
	str = new char[len + 1];
	std::strcpy(str, s);
	num_strings++;
}
String::String()
{
	len = 4;
	str = new char[1];
	str[0] = '\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;
}
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;
}
String & String::operator=(const char *s)
{
	delete[] str;
	len = std::strlen(s);
	str = new char[len + 1];
	std::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 (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);
}
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;
	while (is && is.get() != '\n')
		continue;
	return is;
}
String operator+(const char * s, const String & st)
{
	int i = strlen(s) + st.len;
	char *temp = new char[i + 1];
	std::strcpy(temp, s);
	std::strcat(temp, st.str);
	temp[i] = '\0';
	return String(temp);
}

String operator+(const String & st, const String &st1)
{
	int i = st.len + st1.len;
	char *temp = new char[i + 1];
	std::strcpy(temp, st.str);
	std::strcat(temp, st1.str);
	temp[i] = '\0';
	return String(temp);
}
void String::stringlow()
{
	for (int i = 0; i < len + 1; ++i)
		str[i] = tolower(str[i]);
}
void String::stringup()
{
	for (int i = 0; i < len + 1; ++i)
		str[i] = toupper(str[i]);

}
int String::count(char a)
{
	int n = 0;
	for (int i = 0; i < len + 1; ++i)
		if (str[i] == a)
			++n;
	return n;
}
#endif // STRING2_H_H
#include "String.h"
#include <iostream>
using namespace std;
int main()
{
	String s1(" and I am a c++ student.");
	String s2 = "Please enter your name: ";
	String s3;
	String s4("asd");
	cout << s2;
	cin >> s3;
	s2 = "My name is " + s3;
	cout << s2 << ".\n";
	s2 = s2 + s1;
	s2.stringup();
	cout << "The string\n" << s2 << "\ncontains " << s2.count('A')
		<< " 'A' characters int 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;
}

3.

Stock.h

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

Stock::Stock()
{
	company = nullptr;
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}
Stock::Stock(const char * s, long n, double pr)
{
	int i = strlen(s);
	company = new char[i + 1];
	strcpy(company, s);
	if (n < 0)
	{
		cout << "Number of shares can't be negative; "
			<< company << " shares set 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)
	{
		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)
{
	if (num < 0)
	{
		cout << "Number of shares sold can't be negative. "
			<< "Transaction is aborted.\n";
	}
	else if (num > shares)
	{
		cout << "You can't sell more than you have! "
			<< "Transaction is aborted.\n";
	}
	else
	{
		shares -= num;
		share_val = price;
		set_tot();
	}
}
void Stock::updata(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;
}
ostream & operator<<(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);
	return os;
}
#endif

main.cpp

#include "Stock.h"
const int STKS = 4;
int main()
{
	Stock stocks[STKS] = {
		Stock("NanoSmart", 12, 20.0),
		Stock("Boffo objects", 200, 2.0),
		Stock("Monolithic Obelistks", 130, 3.25),
		Stock("Fleep Enterprises", 60, 6.5)
	};
	std::cout << "Stock holdings:\n";
	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 << "\nMost valuable holding:\n";
	std::cout << *top;
	return 0;
}

4.

Stack.h

#ifndef STACK_H_
#define 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);
};
Stack::Stack(int n)
{
	pitems = new Item[n];
	Size = n;
	top = 0;
}
Stack::Stack(const Stack & st)
{
	pitems = new Item[st.Size];
	Size = st.Size;
	top = st.top;
	for (int i = 0; i < top; i++)
		pitems[i] = st.pitems[i];
}
Stack::~Stack()
{
	delete[] pitems;

}
bool Stack::isempty() const
{
	return top == 0;
}
bool Stack::isfull() const
{
	return top == Size;
}
bool Stack::push(const Item & item)
{
	if (isfull())
		return false;
	else
		pitems[top++] = item;
	return true;
}
bool Stack::pop(Item & item)
{
	if (isempty())
		return false;
	else
		item = pitems[--top];
	return true;
}
Stack &Stack::operator=(const Stack & st)
{
	if (this == &st)
		return *this;
	delete[] pitems;
	pitems = new Item[st.Size];
	Size = st.Size;
	top = st.top;
	for (int i = 0; i < top; ++i)
		pitems[i] = st.pitems[i];
	return *this;
}
#endif

Stack.h

#include "Stack.h"
using std::cout;
int main()
{
	Stack s(5);
	Stack s1(5);
	s.push(100);
	s.push(200);
	s1 = s;
	Stack s3(s);
	Item a, b;
	s1.pop(a);
	s1.pop(b);
	cout << a << " " << b << '\n';
	s3.pop(a);
	s3.pop(b);
	cout << a << " " << b << '\n';
	return 0;
}

5.

Queue.h

#ifndef QUEUE_H_
#define QUEUE_H_
#include <cstdlib>
class Customer
{
private:
	long arrive;
	int processtime;
public:
	Customer() { arrive = processtime = 0; }
	void Set(long when);
	long when() const { return arrive; }
	int ptime() const { return 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);
};

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() 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 = NULL;
	items++;
	if (Front == NULL)
		Front = add;
	else
		rear->next = add;
	rear = add;
	return true;
}

bool Queue::dequeue(Item & item)
{
	if (Front == NULL)
		return false;
	item = Front->item;
	items--;
	Node * temp = Front;
	Front = Front->next;
	delete temp;
	if (items == 0)
		rear = NULL;
	return true;
}

void Customer::Set(long when)
{
	processtime = std::rand() % 3 + 1;
	arrive = when;
}
#endif

main.cpp

#include "Queue.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
const int MIN_PER_HR = 60;

bool newcustomer(double x);
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 line(qs);
	cout << "Enter the average number of 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 wait_time = 0;
	long line_wait = 0;

	long turnaways1 = 0;
	long customers1 = 0;
	long served1 = 0;
	long sum_line1 = 0;
	int wait_time1 = 0;
	long line_wait1 = 0;
	for (int cycle = 0; cycle < cyclelimit; cycle++)
	{
		if (newcustomer(min_per_cust))
		{
			if (line.isfull())
				turnaways++;
			else
			{
				customers++;
				temp.Set(cycle);
				line.enqueue(temp);
			}
		}
		if (wait_time <= 0 && !line.isempty())
		{
			line.dequeue(temp);
			wait_time = temp.ptime();
			line_wait += cycle - temp.when();
			served++;
		}
		if (wait_time > 0)
			wait_time--;
		sum_line += line.queuecount();
	}
	if (customers > 0)
	{
		cout << "customers accepted: " << customers << endl;
		cout << "  customers served: " << served << endl;
		cout << "        turnaway:   " << turnaways << endl;
		cout << "average queue size: ";
		cout.precision(2);
		cout.setf(ios_base::fixed, ios_base::floatfield);
		cout << (double)sum_line / cyclelimit << endl;
		cout << " average wait time: "
			<< (double)line_wait / served << " minutes\n";
	}
	else
		cout << "No customers!\n";
	cout << "Done!\n";

	return 0;
}
bool newcustomer(double x)
{
	return (std::rand() * x / RAND_MAX < 1);
}