C++ Primer Plus 第十二章 课后编程练习题1-6

//1题//////////////////////////////////////////////////////////////////////////////////
//类定义
#ifndef cow_hpp
#define cow_hpp

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

#endif /* cow_hpp */

//类函数定义
#include
#include “cow.hpp”
#include
//默认构造函数
Cow::Cow()
{
name[0] = ‘\0’;
hobby = new char[4];
hobby = nullptr;
weight = 0.0;
std::cout <<“调用默认构造函数\n”;
}

//构造函数
Cow::Cow(const char * nm, const char * ho, double wt)
{
int len;
len = strlen(ho);
hobby = new char[len +1];
std::strncpy(name, nm, 20);
std::strcpy(hobby, ho);
weight = wt;
std::cout <<“调用构造函数\n”;
}

Cow::Cow(const Cow & c)
{
delete [] hobby;
int len;
len = strlen(c.hobby);
hobby = new char[len +1];
std::strcpy(name, c.name);
std::strcpy(hobby, c.hobby);
weight = c.weight;
std::cout <<“调用复制构造函数\n”;
}

Cow::~Cow()
{
delete [] hobby;
name[0] = ‘\0’;
weight = 0.0;
std::cout <<“调用析构函数\n”;
}

Cow & Cow::operator=(const Cow & c)
{
if (this == &c)
return *this;
delete [] hobby;
int len;
len = strlen(c.hobby);
hobby = new char[len +1];
std::strcpy(name, c.name);
std::strcpy(hobby, c.hobby);
weight = c.weight;
std::cout <<“重载=运算符函数\n”;
return *this;
}

void Cow::ShowCow()const
{
std::cout <<"name = " << name << std::endl;
std::cout <<"hobby = " << hobby << std::endl;
std::cout <<"weight = " << weight << std::endl;
}

//main 小程序
#include
#include “cow.hpp”
int main()
{
Cow cow1;
Cow cow2(“aaa”, “bbb”, 12.9);
cow1 = cow2;
cow1.ShowCow();
Cow cow3(cow2);
cow3.ShowCow();
Cow * cow4 = new Cow;
*cow4 = cow2;
cow4->ShowCow();
delete cow4;
return 0;
}

//2题//////////////////////////////////////////////////////////////////////////////////
//类定义
#ifndef string1_hpp
#define string1_hpp

#include
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;}
void Stringlow();
void Stringup();
int has(char c);
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 & st1, const String &st2);
friend bool operator==(const String & st1, const String &st2);
friend ostream & operator<<(ostream & os, const String &st);
friend istream & operator>>(istream & is, String &st);
friend char * operator+(const String & st1, const String &st2);
static int HowMany();
};

#endif /* string1_hpp */

//类函数定义
#include “String2.hpp”
#include
#include
using std::cin;
using std::cout;
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(const String & st)
{
num_strings++;
len = st.len;
str = new char[len + 1];
std::strcpy(str, st.str);
}

String::String()
{
len = 4;
str = new char[1];
str[0] = ‘\0’;
num_strings++;
}

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];
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;
}
//转换为小写
void String::Stringlow()
{
len = strlen(str);
for (int i = 0; i < len; i++)
str[i] = tolower(str[i]);
}
//转换为大写
void String::Stringup()
{
len = strlen(str);
for (int i = 0; i < len; i++)
str[i] = toupper(str[i]);
}
int String::has(char c)
{
int num = 0;
len = strlen(str);
for (int i = 0; i < len; i++)
if (c == str[i])
num++;
return num;
}
char * operator+(const String & st1, const String &st2)
{
int total_len = strlen(st1.str) + strlen(st2.str);
char * total_str = new char[total_len + 1];
std::strcpy(total_str, st1.str);
std::strcat(total_str, st2.str);
//char * st1_str, * st2_str;
//st1_str = new (total_str) char[std::strlen(st1.str)];
//st2_str = new (total_str + std::strlen(st1.str)) char[std::strlen(st2.str)];
return total_str;
}

//3题//////////////////////////////////////////////////////////////////////////////////
//类定义
#ifndef Stock1_hpp
#define Stock1_hpp
#include

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 * co, long n = 0, double pr = 0.0);
Stock(const Stock & s);
~Stock();
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
Stock & operator=(const Stock & s);
friend std::ostream & operator<<(std::ostream & os, const Stock & s);
const Stock & topval(const Stock & s) const;
};

#endif /* Stock1_hpp */

//类函数定义
#include
#include
#include
#include “Stock1.hpp”
using namespace std;
Stock::Stock()
{
company = new char[strlen(“no name”) + 1];
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const char * co, long n, double pr)
{
company = new char[strlen(co) + 1];
if ( n < 0)
{
cout <<“Number of shares can’t be negative; "
<< company <<” shares set to 0.\n";
shares = 0;
}
else
shares = n;
strcpy(company, co);
share_val = pr;
set_tot();
}
Stock::Stock(const Stock & s)
{
delete [] company;
company = new char[strlen(s.company) + 1];
strcpy(company, s.company);
shares = s.shares;
share_val = s.share_val;
total_val = s.total_val;
}
Stock::~Stock()
{
delete [] company;
}
void Stock::buy(long num, double price)
{
if (num < 0)
{
cout <<"Number of shares purchased can’t 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::update(double price)
{
share_val = price;
set_tot();
}

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 << '\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;

}

Stock & Stock::operator=(const Stock & s)
{
if (this == &s)
return *this;
delete [] company;
company = new char[strlen(s.company) + 1];
strcpy(company, s.company);
shares = s.shares;
share_val = s.share_val;
set_tot();
return *this;
}

const Stock & Stock::topval(const Stock & s) const
{
if (s.total_val > total_val)
return s;
else
return *this;
}

//main()
#include
#include “Stock1.hpp”

const int STKS = 4;
int main()
{
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++)
    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题//////////////////////////////////////////////////////////////////////////////////
//类函数定义
#include
#include “stack2.hpp”
Stack::Stack(int n)
{
pitems = new Item[n];
size = n;
top = 0;
}
Stack::Stack(const Stack & st)
{
delete [] pitems;
pitems = new Item[st.size];
for (int i = 0; i < st.size; i++)
pitems[i] = st.pitems[i];
size = st.size;
top = st.top;
}
Stack::~Stack()
{
delete [] pitems;
std::cout <<“NULL\n”;
}
bool Stack::isempty()const
{
if (top == 0)
return true;
else
return false;
}
bool Stack::isfull()const
{
if (top >= size)
return true;
else
return false;
}
bool Stack::push(const Item & item)
{
if (top >= size)
{
std::cout <<“Pitems is full!\n”;
return false;
}
else
{
pitems[top] = item;
top++;
}
return true;
}

bool Stack::pop(Item & item)
{
if (top == 0)
{
std::cout <<“Pitems is empty!\n”;
return false;
}
else
{
item = pitems[top-1];
top–;
return true;
}
}
Stack & Stack::operator=(const Stack & st)
{
delete [] pitems;
pitems = new Item[st.size];
for (int i = 0; i < st.size; i++)
pitems[i] = st.pitems[i];
size = st.size;
top = st.top;

return *this;

}

void Stack::Show()const
{
for (int i = 0; i < 5; i++)
std::cout <<“Pitems[” << i+1 <<"] = " << pitems[i] << std::endl;
std::cout <<"size = " << size << std::endl;
std::cout <<"top = " << top << std::endl;
}

//检验程序
#include
#include “stack2.hpp”

int main()
{
using namespace std;
Stack st;
cout << “Is st empty:”;
cout << st.isempty() << endl;
cout << “Is st full:”;
cout << st.isfull() << endl;

Item it[10];
cout << "Push to st:";
for(int i=0;i<11;i++)
{
    it[i]=i+1;
    st.push(it[i]);
    cout << it[i] << " ";
}
cout << "\nIs st full:";
cout << st.isfull() << endl;

Stack po;
cout << "\nAt first\nIs po empty:";
cout << po.isempty() << endl;
po = st;
cout << "\nAfter po = st\nIs po empty:";
cout << po.isempty();
cout << "\nIs po full:";
cout << po.isfull() << endl;

cout << "\nPop to st:";
for(int i=0;i<10;i++)
{
    st.pop(it[i]);
    cout << it[i] << " ";
}
cout << "\nIs st empty:";
cout << st.isempty() << endl;
return 0;

}

//6题/////////////////////////////////////////////////////////////////////////////////////////////////

//类定义
//比较人数
friend bool operator>(const Queue & item1, const Queue & item2);

//类函数定义
//比较人数
bool operator>(const Queue & item1, const Queue & item2)
{
return item1.items > item2.items;
}

//main()
#include
#include
#include
#include “queue.hpp”
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 maxmium size of queue: ";
int qs;
cin >> qs;
Queue line1(qs);//设有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 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 || line1.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_wait += cycle - temp.when();
        served++;
    }
    if (wait2_time <= 0 && !line2.isempty())
    {
        line2.dequeue(temp);
        wait2_time = temp.ptime();
        line2_wait += cycle - temp.when();
        served++;
    }
    if (wait1_time > 0)
        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;

}

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

发布了85 篇原创文章 · 获赞 1 · 访问量 1889

猜你喜欢

转载自blog.csdn.net/Tekkenwxp/article/details/104423510