目录
课后习题
习题1
#include <iostream>
#include <cstring>
using namespace std;
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();
void ShowCow() const;
};
Cow::Cow() {}
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; }
void Cow::ShowCow() const
{
cout << name << endl;
cout << hobby << endl;
cout << weight << endl;
}
int main()
{
Cow cow;
Cow ccc("adads", "dsdfsad", 34);
cow = ccc;
cow.ShowCow();
ccc.ShowCow();
}
习题2
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
class String
{
char* mp_text;
unsigned m_text_length;
void assignMember(const char* text)
{
m_text_length = strlen(text);
mp_text = new char[m_text_length + 1];
strcpy(mp_text, text);
}
public:
static const unsigned k_buffer_max_size = 256;
const char* toCstr() const
{
return (mp_text);
}
String(const char* text = "")
{
assignMember(text);
}
String(const String& str)
{
assignMember(str.toCstr());
}
~String()
{
delete[] mp_text;
}
unsigned getLength() const
{
return (m_text_length);
}
void stringup()
{
for (unsigned i = 0; i < m_text_length; ++i)
mp_text[i] = (char)toupper(mp_text[i]);
}
void stringlow()
{
for (unsigned i = 0; i < m_text_length; ++i)
mp_text[i] = (char)tolower((int)mp_text[i]);
}
unsigned has(char ch) const
{
unsigned cnt = 0;
for (unsigned i = 0; i < m_text_length; ++i)
if (ch == mp_text[i])
++cnt;
return (cnt);
}
String& operator= (const String& str)
{
if (&str == this)
return (*this);
delete[] mp_text;
assignMember(str.toCstr());
return (*this);
}
String & operator+= (const String& str)
{
return (*this += str);
}
char& operator[] (unsigned idx)
{
return (mp_text[idx]);
}
const char & operator[] (unsigned idx) const
{
return (mp_text[idx]);
}
friend ostream & operator<< (ostream& os, const String& str)
{
os << str.toCstr();
return (os);
}
friend istream & operator>> (istream& is, String& str)
{
char txt[k_buffer_max_size];
if (is >> txt)
str = txt;
is.ignore(k_buffer_max_size, '\n');
return (is);
}
friend bool operator< (const String& lvalue, const String& rvalue)
{
return (strcmp(lvalue.toCstr(), rvalue.toCstr()) < 0);
}
friend bool operator> (const String& lvalue, const String& rvalue)
{
return (rvalue < lvalue);
}
friend bool operator== (const String& lvalue, const String& rvalue)
{
return (!(lvalue < rvalue) && !(lvalue > rvalue));
}
friend bool operator<= (const String& lvalue, const String& rvalue)
{
return (!(lvalue > rvalue));
}
friend bool operator>= (const String& lvalue, const String& rvalue)
{
return (!(lvalue < rvalue));
}
friend String operator+ (const String& lvalue, const String& rvalue)
{
char* p_txt = new char[lvalue.getLength() + rvalue.getLength() + 1];
strcpy(p_txt, lvalue.toCstr());
strcat(p_txt, rvalue.toCstr());
String tmp(p_txt);
delete[] p_txt;
return (tmp);
}
};
int main()
{
String s1(" and I am a C++ student.");
String s2 = "Please enter your name: ";
String s3;
cout << s2;
// overloaded << operator
cin >> s3;
// overloaded >> operator
s2 = "My name is " + s3;
// overloaded =, + operators
cout << s2 << ".\n";
s2 = s2 + s1;
s2.stringup();
// converts string to uppercase
cout << "The string\n" << s2 << "\ncontains " << s2.has('A')
<< " 'A' characters in it.\n";
s1 = "red";
// tstring(const char *),
// then tstring & operator=(const string&)
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();
// converts string to lowercase
for (int i = 0; i < 3; i++)
{
if (ans == rgb[i]) // overloaded == operator
{
cout << "That's right!\n";
success = true;
break;
}
}
if (success)
break;
else
cout << "Try again!\n";
}
cout << "Bye" << endl;
}
习题3
#include <iostream>
#include <cstring>
using namespace std;
class Stock
{
char *company;
int shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; };
public:
Stock() {
company = new char[8];
strcpy(company, "no name");
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock(const char *co, long n = 0, double pr = 0)
{
int len = strlen(co);
company = new char[len + 1];
strcpy(company, co);
if (n < 0)
{
cout << "Number of shares can't be negative;"
<< company << " shares set to 0" << endl;
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}
~Stock()
{
delete[]company;
}
void buy(long num, double price)
{
if (num < 0)
{
cout << "Number of shares purchase can't be negative."
<< " Transaction is aborted." << endl;
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void sell(long num, double price)
{
if (num < 0)
{
cout << "Number of shares sold can't be negative."
<< "Transaction is aborted." << endl;
}
else if (num > shares)
{
cout << "You can't sell more than you have!"
<< "Transaction is aborted." << endl;
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void update(double price)
{
share_val = price;
set_tot();
}
const Stock &topval(const Stock &s)const
{
if (s.total_val > total_val)
return s;
else
return *this;
}
friend ostream &operator<<(ostream &os, const Stock &s)
{
ios_base::fmtflags orig = os.setf(ios_base::fixed, ios_base::floatfield);
streamsize prec = os.precision(3);
os << "Company:" << s.company
<< " Shares:" << s.shares << endl;
os << " Share Price:$" << s.share_val;
os.precision(2);
os << " Total Worth:&" << s.total_val << endl;
os.setf(orig, ios_base::floatfield);
os.precision(prec);
return os;
}
};
const int STKS = 4;
int main()
{
// create an array of initialized objects
Stock stocks[STKS] = {
Stock("NanoSmart", 12, 20.0),
Stock("Boffo Objects", 200, 2.0),
Stock("Monolithic Obelisks", 130, 3.25),
Stock("Fleep Enterprises", 60, 6.5)
};
cout << "Stock holdings:\n";
int st;
for (st = 0; st < STKS; st++)
cout << stocks[st];
// set pointer to first element
const Stock * top = &stocks[0];
for (st = 1; st < STKS; st++)
top = &top->topval(stocks[st]);
// now top points to the most valuable holding
cout << "\nMost valuable holding:\n";
cout << *top;
return 0;
}
习题4
#include <iostream>
using namespace std;
typedef unsigned long Item;
class Stack
{
enum { MAX = 10 };
Item * items;
int size;
int top;
public:
Stack(int n = MAX)
{
items = new Item[MAX];
top = 0;
size = 0;
}
Stack(const Stack &st)
{
items = new Item[st.size];
top = 0;
size = 0;
for (int i = 0; i < st.size; i++)
{
items[i] = st.items[i];
size++;
top++;
}
}
~Stack()
{
delete[] items;
}
bool isEmpty()
{
return top == 0;
}
bool isFull()
{
return top == MAX;
}
bool push(const Item &it)
{
if (isFull())
cout << "error! Stack is full!" << endl;
else
{
items[top++] = it;
size++;
return true;
}
return false;
}
bool pop(Item &item)
{
if (isEmpty())
cout << "error! Stack is empty!" << endl;
else
{
item = items[top--];
size--;
return true;
}
return false;
}
Stack & operator = (Stack &st)
{
delete[] items;
items = new Item[st.size];
top = 0;
size = 0;
for (int i = 0; i < st.size; i++)
{
items[i] = st.items[i];
size++;
top++;
}
return (*this);
}
friend ostream & operator<<(ostream &os, const Stack & st)
{
os << "This Stack is:" << endl;
int len = st.top - 1;
while (len != -1)
{
cout << st.items[len] << endl;
len--;
}
return os;
}
};
int main()
{
Stack s;
Item it[20] = { 0 };
for (int i = 0; i < 11; i++)
{
it[i] = i + 1;
s.push(it[i]);
}
cout << s;
Stack s1(s);
cout << "s1=" << s1;
Stack s2 = s;
cout << s;
}
习题5&6
// queue.h -- interface for a queue
#ifndef QUEUE_H_
#define QUEUE_H_
// This queue will contain Customer items
class Customer
{
private:
long arrive; // arrival time for customer
int processtime; // processing time for customer
public:
Customer() : arrive(0), processtime(0) {}
void set(long when);
long when() const { return arrive; }
int ptime() const { return processtime; }
};
typedef Customer Item;
class Queue
{
private:
// class scope definitions
// Node is a nested structure definition local to this class
struct Node { Item item; struct Node * next; };
enum { Q_SIZE = 10 };
// private class members
Node * front; // pointer to front of Queue
Node * rear; // pointer to rear of Queue
int items; // current number of items in Queue
const int qsize; // maximum number of items in Queue
// preemptive definitions to prevent public copying
Queue(const Queue & q) : qsize(0) { }
Queue & operator=(const Queue & q) { return *this; }
public:
Queue(int qs = Q_SIZE); // create queue with a qs limit
~Queue();
bool isempty() const;
bool isfull() const;
int queuecount() const;
bool enqueue(const Item &item); // add item to end
bool dequeue(Item &item); // remove item from front
};
#endif
// queue.cpp -- Queue and Customer methods
#include "queue.h"
#include <cstdlib> // (or stdlib.h) for rand()
// Queue methods
Queue::Queue(int qs) : qsize(qs)
{
front = rear = NULL;// or nullptr
items = 0;
}
Queue::~Queue()
{
Node * temp;
while (front != NULL) // while queue is not yet empty
{
temp = front; // save address of front item
front = front->next;// reset pointer to next item
delete temp; // delete former front
}
}
bool Queue::isempty() const
{
return items == 0;
}
bool Queue::isfull() const
{
return items == qsize;
}
int Queue::queuecount() const
{
return items;
}
// Add item to queue
bool Queue::enqueue(const Item & item)
{
if (isfull())
return false;
Node * add = new Node; // create node
// on failure, new throws std::bad_alloc exception
add->item = item; // set node pointers
add->next = NULL; // or nullptr;
items++;
if (front == NULL) // if queue is empty,
front = add; // place item at front
else
rear->next = add; // else place at rear
rear = add; // have rear point to new node
return true;
}
// Place front item into item variable and remove from queue
bool Queue::dequeue(Item & item)
{
if (front == NULL)
return false;
item = front->item; // set item to first item in queue
items--;
Node * temp = front;// save location of first item
front = front->next;// reset front to next item
delete temp; // delete former first item
if (items == 0)
rear = NULL;
return true;
}
// customer method
// when is the time at which the customer arrives
// the arrival time is set to when and the processing
// time set to a random value in the range 1 - 3
void Customer::set(long when)
{
processtime = std::rand() % 3 + 1;
arrive = when;
}
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include "queue.h"
const int MIN_PER_HR = 60;
bool newcustomer(double x); // is there a new customer?
int main()
{
using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
// setting things up
std::srand(std::time(0)); // random initializing of rand()
cout << "Case Study: Bank of Heather Automatic Teller\n";
cout << "Enter maximum size of queue: ";
int qs;
cin >> qs;
Queue line(qs); // line queue holds up to qs people
cout << "Enter the number of simulation hours: ";
int hours; // hours of simulation
cin >> hours;
// simulation will run 1 cycle per minute
long cyclelimit = MIN_PER_HR * hours; // # of cycles
cout << "Enter the average number of customers per hour: ";
double perhour; // average # of arrival per hour
cin >> perhour;
double min_per_cust;// average time between arrivals
min_per_cust = MIN_PER_HR / perhour;
Item temp; // new customer data
long turnaways = 0; // turned away by full queue
long customers = 0; // joined the queue
long served = 0; // served during the simulation
long sum_line = 0; // cumulative line length
int wait_time = 0; // time until autoteller is free
long line_wait = 0; // cumulative time in line
// running the simulation
for (int cycle = 0; cycle < cyclelimit; cycle++)
{
if (newcustomer(min_per_cust)) // have newcomer
{
if (line.isfull())
turnaways++;
else
{
customers++;
temp.set(cycle); // cycle = time of arrival
line.enqueue(temp); // add newcomer to line
}
}
if (wait_time <= 0 && !line.isempty())
{
line.dequeue(temp); // attend next customer
wait_time = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time > 0)
wait_time--;
sum_line += line.queuecount();
}
// reporting results
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";
// cin.get();
// cin.get();
return 0;
}
// x = average time, in minutes, between customers
// return value is true if customer shows up this minute
bool newcustomer(double x)
{
return (std::rand() * x / RAND_MAX < 1);
}