编程练习
1.对于下面的类声明:
//Cow.h
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.cpp
//
// Created by Reza on 2021/3/4.
//
#include "Cow.h"
#include
#include
Cow::Cow() {
hobby = new char [5];
name[0]='\0';
hobby= "None";
weight=0;
}
Cow::Cow(const char *nm, const char *ho, double wt) {
hobby = new char [strlen(ho)+1];
strcpy(name,nm);
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;
hobby = new char [strlen(c.hobby)+1];
strcpy(name,c.name);
strcpy(hobby,c.hobby);
weight=c.weight;
return *this;
}
void Cow::ShowCow() const {
std::cout << "fullname: " << name << "\n";
std::cout << "hobby: " << hobby << "\n";
std::cout << "weight: " << weight <<"\n";
}
main.cpp
#include "Cow.h"
int main() {
Cow c1;
c1.ShowCow();
Cow c2("c2","eating",66);
c2.ShowCow();
Cow c3=c2;
c3.ShowCow();
Cow c4;
c4=c3;
c4.ShowCow();
}
2.通过完成下面的构造来改进String类声明(即将String1.h升级为String2.h)。
String2.h
//
// Created by Reza on 2021/3/5.
//
#ifndef STRING_STRING2_H
#define STRING_STRING2_H
// string1.h -- fixed and augmented string class definition
#ifndef STRING1_H_
#define STRING1_H_
#include
using std::ostream;
using std::istream;
class String
{
private:
char * str; // pointer to string
int len; // length of string
static int num_strings; // number of objects
static const int CINLIM = 80; // cin input limit
public:
// constructors and other methods
String(const char * s); // constructor
String(); // default constructor
String(const String &); // copy constructor
~String(); // destructor
int length () const { return len; }
// overloaded operator methods
String & operator=(const String &);
String & operator=(const char *);
String operator+(const String & s ) const;
String operator+(const char *s) const;
char & operator[](int i);
const char & operator[](int i) const;
// overloaded operator friends
friend String operator+(const char * st1,const String &st2);
friend bool operator<(const String &st, const String &st2);
friend bool operator>(const String &st1, 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);
//member function
void Stringlow();
void stringup();
int has(char s);
// static function
static int HowMany();
};
#endif
#endif //STRING_STRING2_H
String2.cpp
//
// Created by Reza on 2021/3/5.
//
// string1.cpp -- String class methods
#include // string.h for some
#include
#include "string2.h" // includes
using std::cin;
using std::cout;
// initializing static class member
int String::num_strings = 0;
// static method
int String::HowMany()
{
return num_strings;
}
// class methods
String::String(const char * s) // construct String from C string
{
len = std::strlen(s); // set size
str = new char[len + 1]; // allot storage
std::strcpy(str, s); // initialize pointer
num_strings++; // set object count
}
String::String() // default constructor
{
len = 4;
str = new char[1];
str[0] = '\0'; // default string
num_strings++;
}
String::String(const String & st)
{
num_strings++; // handle static member update
len = st.len; // same length
str = new char [len + 1]; // allot space
std::strcpy(str, st.str); // copy string to new location
}
String::~String() // necessary destructor
{
--num_strings; // required
delete [] str; // required
}
//member function
void String::Stringlow() {
for (int i = 0; i < strlen(str); ++i) {
str[i]=tolower(str[i]);
}
}
void String::stringup() {
for (int i = 0; i < strlen(str); ++i) {
str[i]=toupper(str[i]);
}
}
int String::has(char s) {
int count=0;
for (int i = 0; i < strlen(str); ++i) {
if (s==str[i])
count++;
}
return count;
}
// overloaded operator methods
// assign a String to a String
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;
}
// assign a C string to a String
String & String::operator=(const char * s)
{
delete [] str;
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
return *this;
}
// read-write char access for non-const String
char & String::operator[](int i)
{
return str[i];
}
// read-only char access for const String
const char & String::operator[](int i) const
{
return str[i];
}
String String::operator+(const String &s) const {
int len = strlen(str)+strlen(s.str);
char * str_sum = new char [len+1];
strcpy(str_sum,str);
strcat(str_sum,s.str);
String temp = str_sum;
delete [] str_sum;
return temp;
}
String String::operator+(const char *s) const {
String temp=s;
String sum = temp + *this;
return sum;
}
// overloaded operator friends
String operator+(const char * st1, const String & st2)
{
return st2 + st1;
}
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);
}
// simple String output
ostream & operator<<(ostream & os, const String & st)
{
os << st.str;
return os;
}
// quick and dirty String input
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;
}
main.cpp
#include
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;
}
3.新编写程序清单10.7和程序清单10.8描述的 Stock 类,使之使用动态分配的内存,而不是 string 类对象来存储股票名称。另外,使用重载的 operator << () 定义代替 show() 成员函数。再使用程序清单 10.9 测试新的定义程序。
Stock.h
//
// Created by Reza on 2021/3/6.
//
#ifndef STOCK_STOCK_H
#define STOCK_STOCK_H
#include
using namespace std;
class Stock
{
private:
char * company;
int shares;
double share_val;
double total_val;
void set_tot() { total_val = shares * share_val; }
public:
Stock(); // default constructor
Stock(const char * s, long n = 0, double pr = 0.0);
~Stock(); // do-nothing destructor
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
const Stock & topval(const Stock & s) const;
friend ostream & operator << (ostream & os , const Stock & st);
};
#endif
Stock.cpp
#include
#include
#include "Stock.h"
using namespace std;
// constructors
Stock::Stock() // default constructor
{
company = nullptr;
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char *s, long n, double pr)
{
int len = strlen(s);
company = new char [len];
strcpy(company,s);
if (n < 0)
{
std::cout << "Number of shares can't be negative; "
<< company << " shares set to 0.\n";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}
// class destructor
Stock::~Stock() // quiet class destructor
{
delete [] company;
}
// other methods
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 have! "
<< "Transaction is aborted.\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;
}
ostream & operator << (ostream & os, const Stock & st){
ios_base::fmtflags orig =
cout.setf(ios_base::fixed, ios_base::floatfield);
streamsize prec = cout.precision(3);
os << "company: "<< st.company << endl
<< "shares : " << st.shares << endl
<< "share value "<
main.cpp
// usestok2.cpp -- using the Stock class
// compile with stock20.cpp
#include
#include "Stock.h"
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)
};
std::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
std::cout << "\nMost valuable holding:\n";
cout << *top;
}
// std::cin.get();
return 0;
}
4.请看下面程序清单10.10定义的Stack类的变量:
Stack.h
//
// Created by Reza on 2021/3/6.
//
#ifndef STACK_STACK_H
#define STACK_STACK_H
typedef unsigned long Item;
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Item * pitems;
int size;
int top; // index for top stack item
public:
Stack(int n = MAX);
Stack(const Stack & st);
~Stack();
bool isempty() const;
bool isfull() const;
// push() returns false if stack already is full, true otherwise
bool push(const Item & item); // add item to stack
// pop() returns false if stack already is empty, true otherwise
bool pop(Item & item); // pop top into item
Stack & operator=(const Stack & st);
};
#endif //STACK_STACK_H
Stack.cpp
//
// Created by Reza on 2021/3/6.
//
// stack.cpp -- Stack member functions
#include "Stack.h"
#include
Stack::Stack(int n) // create an empty stack
{
top = 0;
size = n;
pitems = new Item [size];
}
Stack::Stack(const Stack &st) {
size=st.size;
top=st.top;
pitems = new Item [st.size];
for (int i = 0; i < st.size; ++i) {
pitems[i]=st.pitems[i];
}
}
Stack::~Stack() {
delete [] pitems;
}
bool Stack::isempty() const
{
if(top == 0)
std::cout << "The stack is empty" << std::endl;
else
std::cout << "The stack is not empty" << std::endl;
}
bool Stack::isfull() const
{
if(top == MAX)
std::cout << "The stack is full" << std::endl;
else
std::cout << "The stack is not full" << std::endl;
}
bool Stack::push(const Item & item)
{
if (top < MAX)
{
pitems[top++] = item;
return true;
}
else
return false;
}
bool Stack::pop(Item & item)
{
if (top > 0)
{
item = pitems[--top];
return true;
}
else
return false;
}
Stack & Stack::operator = (const Stack &st) {
if(this == &st)
return *this;
delete [] pitems;
size = st.size;
top = st.top;
pitems = new Item [st.size];
for (int i = 0; i < st.size; ++i) {
pitems[i]=st.pitems[i];
}
return *this;
}
main.cpp
#include
#include "Stack.h"
using namespace std;
int main(){
Stack s1;
Stack s2(10);
s1.isempty();
s1.push(1);
s1.isempty();
for(int i = 0;i < 9;i++)
s1.push(0);
s1.isfull();
Item node;
s1.pop(node);
s1.isfull();
Stack s3=s1;
s3.isfull();
s2=s3;
s2.isfull();
}
5. Heather银行进行的研究表明,ATM客户不希望排队时间不超过1分钟。使用程序清单12.10中的模拟,找出要使平均等候时间为1分钟,每小时到达的客户数应为多少(试验时间不短于100小时)?
由仿真实验可知,当每小时到达的客户数为17-18时,可以使得用户的平均等待时间为1分钟。
6.Heather银行想知道,如果再开设一台ATM,情况将如何。请对模拟进行修改,以包含两个队列。假设当第一台ATM前的排队人数少于第二台ATM时,可会将排在第一队,否则将排在第二队。然后再找出要使平均等候时间为1分钟,每小时到达的客户数应该为多少?(注意,这是一个非线性问题,即将ATM数量加倍,并不能保证每小时处理的客户数量也翻倍,并确保客户等待的时间小于1分钟)
queue.h
//
// Created by Reza on 2021/3/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
//
// Created by Reza on 2021/3/6.
//
// queue.cpp -- Queue and Customer methods
#include "ATM.h"
#include // (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;
}
main.cpp
// bank.cpp -- using the Queue interface
// compile with queue.cpp
#include
#include // for rand() and srand()
#include // for time()
#include "ATM.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_1(qs); // line queue holds up to qs people
Queue line_2(qs);
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_1 = 0; // time until autoteller is free
int wait_time_2 = 0;
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_1.isfull() && line_2.isfull())
turnaways++;
else
{
if (line_1.queuecount() > line_2.queuecount())
{
customers++;
temp.set(cycle);
line_2.enqueue(temp);
}
else
{
customers++;
temp.set(cycle); // cycle = time of arrival
line_1.enqueue(temp); // add newcomer to line
}
}
}
if (wait_time_1<= 0 && !line_1.isempty())
{
line_1.dequeue (temp); // attend next customer
wait_time_1 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time_2 <= 0 && !line_2.isempty())
{
line_2.dequeue (temp); // attend next customer
wait_time_2 = temp.ptime(); // for wait_time minutes
line_wait += cycle - temp.when();
served++;
}
if (wait_time_1 > 0)
wait_time_1--;
if (wait_time_2 > 0)
wait_time_2--;
sum_line += line_1.queuecount() + line_2.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);
}
由仿真实验可知,当每小时到达的客户数为50-51时,可以使得用户的平均等待时间为1分钟。