C++ Class练习

《C++ Primer Plus》
第12章 课后练习2

#ifndef STRING_H_
#define STRING_H_
#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;
        void Stringlow();
        void Stringup();
        int has(const char c);
        String operator+(const String & st1);

        operator char *() 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 char *, const String & st1);
        friend ostream & operator<<(ostream & os, const String & st);
        friend istream & operator>>(istream & is, String & st);

        static int HowMany();
};
#endif
#include <cstring>
#include <cctype>
#include "String.h"
#include <iostream>
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)
{
	delete [] str;
	
	len = strlen(st.str);
	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];
}

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;
}

void String::Stringlow()
{
	for (int i = 0;i < len; i++)
		str[i] = tolower(str[i]);
}

void String::Stringup()
{
	for (int i = 0;i < len; i++)
		str[i] = toupper(str[i]);
}
/* 错误的重载函数,问题是构造temp的时候,已经使用new 分配了固定长度的内存。使用strcat的时候实际上已经内存溢出了.
String String::operator+(const String & st1)
{
	String temp(str);
	strcat(temp.str,st1.str);
	temp.len = strlen(str) + strlen(st1.str) + 1;
	return temp;
}
*/
String String::operator+(const String & st1)
{
	int nlen = strlen(st1.str) + strlen(str) + 1;
	char * nstr = new char[nlen];
	strcpy(nstr,str);
	strcat(nstr,st1.str);
	String temp;
	delete [] temp.str;
	temp.str = nstr;
	return temp;
}

String::operator char *() const
{
	return str;
}

String operator+(const char * st1,const String & st2)
{
	String temp;
	strcat(temp.str,st1);
	strcat(temp.str,st2.str);
	temp.len = strlen(st1) + st2.len;
	return temp;
}

int String::has(const char c)
{
	int count = 0;
	for(int i = 0; i < len; i++)
			if (str[i] == c )
				count++;
	return count;
}
#include <iostream>
using namespace std;
#include "String2.h"
int main()
{
        String s1(" and I am C++ stdudent.");
        String s2 = "Pleas 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章 课后练习6

#ifndef QUEUE_H_
#define QUEUE_H_
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);
};
#endif
#include "queue.h"
#include <cstdlib>
#include <stdio.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() 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;
}

[code lang="C" title="queue.cpp"]

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "queue.h"

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 maximum size of queue: ";
	int qs;
	cin >> qs;
	Queue line1(qs);
	Queue line2(qs);

	cout << "Enter the number of simulation hours: ";
	int hours;
	cin >> hours;

	long cyclelimit = MIN_PER_HR * hours;

	cout << "Enter the average number of customers per hours: ";
	double perhour;
	cin >> perhour;
	double min_per_cust;
	min_per_cust = MIN_PER_HR / perhour ;

	Item temp1,temp2;
	long turnaways = 0;
	long customers = 0;
	long served = 0;
	long sum_line = 0;
	int wait_time1,wait_time2;
	wait_time1 = wait_time2 = 0;
	long line_wait = 0;
	for(int cycle = 0;cycle < cyclelimit; cycle++)
	{
		if (newcustomer(min_per_cust))
		{
			if ( line1.isfull() && line2.isfull() )
				turnaways++;
			else
			{
				customers++;
				if ( line1.isfull() )
				{
					temp2.set(cycle);
					line2.enqueue(temp2);
				}
				else
				{
					temp1.set(cycle);
					line1.enqueue(temp1);
				}
			}
		}
		if (wait_time1 <= 0 && !line1.isempty())
                {
                        line1.dequeue(temp1);
                        wait_time1 = temp1.ptime();
                        line_wait += cycle - temp1.when();
                        served++;
                }
		if (wait_time2 <= 0 && !line2.isempty())
                {
                        line2.dequeue(temp2);
                        wait_time2 = temp2.ptime();
                        line_wait += cycle - temp2.when();
                        served++;
                }
		if(wait_time1 > 0)
			wait_time1--;
		if(wait_time2 > 0)
			wait_time2--;
		sum_line += ( line1.queuecount() + 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) 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);
}